In the previous simple understanding of container queries, it felt similar to media queries.
@container (min-width: 200px) {
.card {
font-size: 1rem;
}
}
@container (min-width: 400px) {
.card {
font-size: 1.2rem;
}
}
@container (min-width: 800px) {
.card {
font-size: 2rem;
}
}
After a detailed understanding, it was found that for container queries, it also has units similar to vw and vh.
There are 6 container query units corresponding to vh and vw.
- cqi: Queries 1% of the container's inline size.
- cqw: Queries 1% of the container's width.
- cqb: Queries 1% of the container's block size.
- cqh: Queries 1% of the container's height.
- cqmin: The smaller value between
cqi
andcqb
. - cqmax: The larger value between
cqi
andcqb
.
cq means container query.
Wow, this is so cool. Knowing the size of the parent element is very useful for many animations, as it makes it easier to control the element's transformation distance.
@keyframes slidein {
from {
transform: translateX(100cqw);
}
to {
transform: translateX(0);
}
}
Similar to vw, these units can also simplify code and make it easier to create responsive code.
.card {
font-size: clamp(1rem, 3cqw , 2rem);
}
We can use cqw to simplify multiple media query writings and use the clamp function to specify the upper and lower limits of the font size. This is very effective for optimizing different resolutions.
more#
Query width
/* Define the container */
.container {
container-type: size;
}
/* Use container queries, apply styles when the container width is greater than or equal to 300px */
@container (min-width: 300px) {
.element {
/* Styles */
}
}
Query aspect ratio
/* Define the container */
.container {
container-type: aspect-ratio;
aspect-ratio: 16 / 9; /* Define the aspect ratio as 16:9 */
}
/* Use container queries, apply styles when the container aspect ratio is greater than or equal to 16:9 */
@container (aspect-ratio >= 16 / 9) {
.element {
/* Styles */
}
}
Query orientation
/* Define the container */
.container {
container-type: inline-size;
}
/* Use container queries, apply styles when the container orientation is landscape */
@container (orientation: landscape) {
.element {
/* Styles */
}
}
Specify container name
/* Define the container and specify the name */
.container {
container-type: size;
container-name: myContainer;
}
/* Use the container name for querying */
@container myContainer (min-width: 600px) {
.element {
/* Styles */
}
}