banner
meanc

meanc

自部署博客在 blog.meanc.cc
twitter
github
discord server

Container queries are not just @container

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.

  1. cqi: Queries 1% of the container's inline size.
  2. cqw: Queries 1% of the container's width.
  3. cqb: Queries 1% of the container's block size.
  4. cqh: Queries 1% of the container's height.
  5. cqmin: The smaller value between cqi and cqb.
  6. cqmax: The larger value between cqi and cqb.

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 */
  }
}
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.