search
HomeWeb Front-endCSS TutorialA Few Times Container Size Queries Would Have Helped Me Out

A Few Times Container Size Queries Would Have Helped Me Out

CSS container query technology is becoming more and more mature, and many developers are beginning to try to apply it to various projects, even if it is just simple experiments. While browser support is not entirely popular, it is practical enough in some projects, but may not be enough to completely replace media queries in older projects.

Container query is indeed very convenient! In fact, I've been in a few situations and I've been very eager to use it, but I'm limited by browser compatibility. If container query can be used at that time, the effect will be better.

All the following demos are best viewed in Chrome or Safari at the time of writing. Firefox plans to provide support in version 109.

Case 1: Card Grid

Everyone should be familiar with this case, right? This is a very common pattern that we almost encounter. But the truth is that if container queries can be used instead of standard media queries, it will save a lot of time and get better results.

Suppose you need to build a card grid that requires each card to maintain a 1:1 aspect ratio:

This is harder than it seems! The problem is that resizing component contents based on viewport width will allow you to be subject to how the component responds to the viewport, and how any other ancestor containers respond to the viewport. For example, if you want the font size of the card title to decrease when it reaches a specific inline size, there is no reliable way to do this.

You can set the font size using vw units, but the component is still bound to the browser's viewport width. This can cause problems when the card grid is used in other contexts that may not have the same breakpoint.

In my actual project, I took the JavaScript method:

  1. Listen to resize events.
  2. Calculate the width of each card.
  3. Add inline font size according to card width.
  4. Use em units to set the internal style.

It looks like a lot of work, right? But this is a stable solution to achieve the desired scaling in different screen sizes and in different contexts.

Container query will be better because it provides Container query units , such as cqw units. As you may have learned, 1cqw is equal to 1% of the width of the container. We also have cqi units, which is a measure of the inline width of the container, and cqb is used for the container block width. So if we have a 500px wide card container, the value of 50cqw is calculated as 250px.

If I can use container query in my card grid, I can set the .card component to container:

<code>.card { 
  container: card / size;
}</code>

I can then set up an internal wrapper with padding using cqw units that scales by 10% of the width of .card:

<code>.card__inner { 
  padding: 10cqw; 
} </code>

This is a good way to consistently scale the spacing between the edge of the card and its contents, regardless of where the card is used at any given viewport width. No media inquiries are required!

Another idea? Use cqw units as the font size of the internal content, and then apply the fill using em units:

<code>.card { 
  container: card / size;
}</code>

5cqw is an arbitrary value - I just selected a value. The padding is still equal to 10cqw, because the em unit is relative to the .card__inner font size!

Did you notice it? 2em relative to the 5cqw font size set on the same container ! The container works differently than we are used to because the em unit is relative to the font size value of the same element. But I quickly noticed that the container query unit is related to the recent parent (also a container) of . For example, in this example, 5cqw does not scale based on the width of the

element:

.card

Instead, it will scale to the nearest parent defined as the container. That's why I set up a
<code>.card__inner { 
  padding: 10cqw; 
} </code>
wrapper.

.card__innerCase 2: Alternating layout

In another project, I also need another card component. This time, I need the card to transition from horizontal layout to vertical layout when the screen becomes smaller...and then go back to horizontal layout again, and back to vertical layout.

I did this daunting job to make the component become portrait within two specific viewport ranges (a salute to the new media query range syntax!), but the problem is that it is then locked on the media query that is set for it, its parent, and anything else that might respond to the viewport width. We need something that works in any situation without worrying about where the content will be interrupted!

Container query can easily solve this problem due to the use of the

rule:

@container

One query, infinitely smooth:
<code>.card__inner { 
  font-size: 5cqw; 
  padding: 2em;
} </code>

But wait! There are some issues you may need to be aware of. Specifically, using such container queries in prop-based design systems can be difficult. For example, this

component might contain child components that rely on prop to change their appearance.

.info-cardWhy is this important? The portrait layout of the card may require alternate styles, but you cannot change the JavaScript prop using CSS. Therefore, you may repeat the style you want. I actually discussed this and how to solve this in another post. If you need to use container queries for a large number of styles, you may need to build an entire design system around them, rather than trying to stuff them into an existing design system that relies on media queries.

Case 3: SVG Stroke

This is another very common pattern I have used recently. If you use container queries, you will get a more complete product. Suppose you have an icon locked with the title:

Even without media queries, it is easy to scale the icon according to the size of the title. However, the problem is that the
<code>.card { 
  container: card / size; 
  container-name: card; 
  font-size: 5cqw; 
}</code>
of SVG can be too thin to notice in smaller sizes, and can be too thick and too conspicuous in larger sizes.

I had to create and apply classes for each icon instance to determine its size and stroke width. This is OK if the icon is next to a title that uses a fixed font size, but it is not as good when using a constantly changing fluid type.

The font size of the title may be based on the viewport width, so the SVG icon needs to be adjusted accordingly and will work properly at any size. You can set the stroke width relative to the font size of the title by using em units. However, if you need to stick to a specific set of stroke sizes, this method doesn't work because it scales linearly - without using media queries on viewport width, you can't adjust it to a specific stroke width value without resorting to media queries on viewport width.

However, if I have the opportunity to use container query, I will do this:

<code>.card { 
  container: card / size;
}</code>

Compare these implementations and see how the container query version captures the SVG's stroke to the specific width I want based on the width of the container.

Additional content: Other types of container size query

OK, I didn't actually encounter this in the actual project. However, when I looked closely at the information about container queries, I noticed that we can query other contents of containers related to container size or physical size.

The examples I've been using in this post mostly query width, maximum and minimum width, height, block size, and inline size.

<code>.card__inner { 
  padding: 10cqw; 
} </code>

But MDN outlines two other things we can query. One is the direction, which makes a lot of sense because we have been using it in media queries. The same is true for container queries:

<code>.card__inner { 
  font-size: 5cqw; 
  padding: 2em;
} </code>

The other is aspect ratio, believe it or not:

<code>.card { 
  container: card / size; 
  container-name: card; 
  font-size: 5cqw; 
}</code>

This is an editable demonstration that can be used to experiment with these two examples:

I haven't really found good use cases for these two yet. If you have any ideas or feel it can help you with your project, please let me know in the comments!

The above is the detailed content of A Few Times Container Size Queries Would Have Helped Me Out. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Lost CSS Tricks of Cohost.orgThe Lost CSS Tricks of Cohost.orgApr 25, 2025 am 09:51 AM

In this post, Blackle Mori shows you a few of the hacks found while trying to push the limits of Cohost’s HTML support. Use these if you dare, lest you too get labelled a CSS criminal.

Next Level CSS Styling for CursorsNext Level CSS Styling for CursorsApr 23, 2025 am 11:04 AM

Custom cursors with CSS are great, but we can take things to the next level with JavaScript. Using JavaScript, we can transition between cursor states, place dynamic text within the cursor, apply complex animations, and apply filters.

Worlds Collide: Keyframe Collision Detection Using Style QueriesWorlds Collide: Keyframe Collision Detection Using Style QueriesApr 23, 2025 am 10:42 AM

Interactive CSS animations with elements ricocheting off each other seem more plausible in 2025. While it’s unnecessary to implement Pong in CSS, the increasing flexibility and power of CSS reinforce Lee's suspicion that one day it will be a

Using CSS backdrop-filter for UI EffectsUsing CSS backdrop-filter for UI EffectsApr 23, 2025 am 10:20 AM

Tips and tricks on utilizing the CSS backdrop-filter property to style user interfaces. You’ll learn how to layer backdrop filters among multiple elements, and integrate them with other CSS graphical effects to create elaborate designs.

SMIL on?SMIL on?Apr 23, 2025 am 09:57 AM

Well, it turns out that SVG's built-in animation features were never deprecated as planned. Sure, CSS and JavaScript are more than capable of carrying the load, but it's good to know that SMIL is not dead in the water as previously

'Pretty' is in the eye of the beholder'Pretty' is in the eye of the beholderApr 23, 2025 am 09:40 AM

Yay, let's jump for text-wrap: pretty landing in Safari Technology Preview! But beware that it's different from how it works in Chromium browsers.

CSS-Tricks Chronicles XLIIICSS-Tricks Chronicles XLIIIApr 23, 2025 am 09:35 AM

This CSS-Tricks update highlights significant progress in the Almanac, recent podcast appearances, a new CSS counters guide, and the addition of several new authors contributing valuable content.

Tailwind's @apply Feature is Better Than it SoundsTailwind's @apply Feature is Better Than it SoundsApr 23, 2025 am 09:23 AM

Most of the time, people showcase Tailwind's @apply feature with one of Tailwind's single-property utilities (which changes a single CSS declaration). When showcased this way, @apply doesn't sound promising at all. So obvio

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)