"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Container Queries in CSS

Container Queries in CSS

Published on 2024-11-12
Browse:983

Container Queries in CSS

First a container must be registered, and it can be queried.

Register a Container

Use a selector to register a container.

.parent {
    container-name: myname;
    container-type: inline-size;
    ... other code
}

or, use the shorthand option

.parent {
    container: myname / inline-size;
    ... other code
}

At the time of registration, two details - type and name - have to specified.

Container Type

container-type: ...

  • size
  • inline-size
  • normal

Container Name

container-name: ;

identifies the container especially useful if you may a scenario of multiple containers.

Query a Container

The container query starts with the @container at-rule followed by the name of the container and the feature query.

div {
    font-size: 2em;
}

@container myname (width: > 30ch)
{
    div {
        font-size: 3em;
    }
}

container query to set font-size for the div inside the myname container to 3em if the feature width is greater than 30ch.

Features to Query

size-query...

  • width
  • height
  • inline-size
  • block-size
  • aspect-ratio
  • orientation

style-query...

  • style(property: value)

property to be checked for value.

for eg

@container contname style('background-color: blue') {
    ... 
    styles 
    ...
}

The container query to apply styles if the background-color of the container contname is blue

Compound Queries

and, or and not can be used to create compound queries

for eg

    @container myname (width>30ch) and (height>100px) {
        ...
    }

    @container myname not (color: blue) {
        ...
    }

Nested Container Queries

Container queries can be nested within other container queries.

for eg

    @container myname (width>30ch) {
        ...
        @container myname (background-color: blue) {
            ...
        }
        @container myname (background-color: red) {
            ...
        }
    }
Release Statement This article is reproduced at: https://dev.to/gajendra/container-queries-in-css-3o6a?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3