Frontend Masters Boost RSS Feed https://frontendmasters.com/blog Helping Your Journey to Senior Developer Fri, 02 Aug 2024 16:49:12 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 225069128 What if you used Container Units for… everything? https://frontendmasters.com/blog/what-if-you-used-container-units-for-everything/ https://frontendmasters.com/blog/what-if-you-used-container-units-for-everything/#respond Fri, 02 Aug 2024 16:49:11 +0000 https://frontendmasters.com/blog/?p=3108 I said to myself I said what if I used container units for every single unit in a design? I was wondering, partially because I thought the answer might be well, everything will probably scale really nicely then. Container units, in case you haven’t heard of them, are unit (like px or rem, but more closely related to viewport units like vw or vi) that are sized relatively to the container that they are in.

Turns out, surprise surprise, that it’s not that easy. There are plenty of things that container queries are awkward at or just not the right unit for.

I had a play with a pretty simple grid of cards of various sizes. Don’t consider this demo in good shape, it’s just what I used to have a plan.

Potential Problem: You Can’t Style The Element You Query

This is a fairly known thing with container queries, but the weirdness with it compounds a bit with container units, as the desire to use those units right away on a container is strong. To be clear, the container units will “work”, they’ll just be based on the next-higher-up container, which if there isn’t a declared one will be the document.

.card-wrap {
  container: cardWrap / inline-size;

  padding: 2cqi;
  border-radius: 4cqi;

  .card {
    border-radius: 4cqi;
  }
}

Above, the border-radius will be different despite looking like it will be the same, because the container the units reference are different.

See how the outer border radius’ match, but the inner card are different and look off on the larger card.

Potential Solution: Style Nothing on the Container

Be vigilant! It will save headaches if you are hardfast when you set a container you do no other size-based styling. If that means adding an extra otherwise meaningless <div> wrapper, well, that’s not ultra ideal as DOM weight does matter, but it’s probably fine.

Potential Problem: Too Small & Too Big

If you only use container units for something like font-size, it’s pretty easy to get into a situation where text, and text-based elements, end up either too big or too small.

Here the text on the larger card feels a bit too big but the tags are OK. The text on the smaller card feels OK, but those tags are too small.

Either is annoying, but too small is also an accessibility failure.

Using container units (or viewport units) alone is a bad practice for text sizing. It’s fixable though.

Potential Solution: Clamp

Making sure text doesn’t get too small or too big is solved with a CSS clamp() function. And while we’re at it, we can sprinkle in a relative unit to make sure that users font sizing preferences are honored.

You can still use container units, but set those limits and use a bit of relative mixed in.

.tag {
  /* Don't */
  font-size: 4cqi;

  /* Do */
  font-size: clamp(16px, 4cqi + 0.5rem, 24px);
}

Potential Problem: Rows vs Columns

One strong use case for a container query is shifting layout at container based breakpoints. If that container goes from wide-and-short to narrow-and-tall, then the width-based (probably the most common) container units will be super different.

Say the container here is the card itself, and you size some icons to work with that context when they are horizontal. But then if you shift the layout to a narrow column for the icons, as the card gets bigger, the sizing doesn’t work in that context now.

Bonus problem: you can’t use container units to set the grid-template-columns as they can never be based on an element that is reliably the same width as the grid.

Instead, if we make the element around the icons the container, and thus it changes width when the layout changes, the change in our icon size can be too dramatic.

Potential Solution: Use a Different Unit

And here’s the rub. You just don’t have to use container units for everything. I doubt anyone ever intended for them to be used that way. It’s just a fun exercise, especially as strong scalability is a great effect.

In this case maybe something like cqmax units would be workable, so the unit is based on the containers longest edge.

.actions {
  container: actions / inline-size;

  svg {
    display: block;
    width: 4cqmax;
    min-width: 24px;
    max-width: 100%;
    aspect-ratio: 1;
  }
}

But… nah. It’s too weird. I’d say just use relative units or pixels or something here.

In the end, if container units are helpful for a scaling effect based on the size of an element you want to achieve, go for it! The support is good. But don’t force it.

If you’re up for a challenge, have a play with it. Try something like converting every unit in a more complex layout like this into containers with container units.

]]>
https://frontendmasters.com/blog/what-if-you-used-container-units-for-everything/feed/ 0 3108
Container Queries and Units https://frontendmasters.com/blog/container-queries-and-units/ https://frontendmasters.com/blog/container-queries-and-units/#respond Thu, 21 Dec 2023 15:41:02 +0000 https://frontendmasters.com/blog/?p=282 Container queries are similar to media queries but allow you set styles based on a particular element’s current size, typically the width. This is super handy because you can write CSS in a way that gives flexibility to the layout!

With @media queries, there’s a tight coupling of the styling of a component’s content and the size of the browser window. This means that the styles within a given component depend on the layout.

With @container queries, we can instead tightly couple the styling of a component’s content with the size of the component itself, regardless of how that component fits into the larger layout. In short, you can set up components to respond to the container size without having to know the breakpoints of the overall page layout. Yay for increased isolation!

Let’s think through an example to illustrate this. Pulling from Michelle Barker’s helpful MDN article about container queries, here’s a mockup:

When there’s more width available, each article preview has the image on the left and copy on the right. When there’s less room available, it stacks the image on top of the content.

Without container queries, we’d have to specify which cards we want to have the vertical layout, which ones should have the horizontal layout, and which should have a bigger image explicitly. When you then consider all possible screen sizes and container layouts, this quickly becomes quite complicated.

Additionally, if there’s a possibility for the sidebar to be collapsed or if you sometimes need to show additional content (like ads) alongside this content, it gets even more complex! Not to mention when the layout gets changed to something else, like switching from 4 columns to 3, you have to go back and adjust everything.

Container queries can help us more easily address this sort of situation in a much more manageable way!

Container queries are separate from, but can be in used in combination with, the contain property The contain property is useful for performance and preventing re-renders and, crucially, the thing that made @container queries possible under the hood.

Block and inline sizing

Before diving further into container queries, it’s important to make sure we have a good understanding of block and inline sizing as it has a large impact on the container-type and the container unit(s) we use.

Inline size is equivalent to width for horizontal writing mode and equivalent to the height for vertical writing modes. The block size is the respective opposite.

Make sure you keep this in mind! The terms “block” and “inline” are from the concept of “logical properties” and the direction CSS has been heading for a while.

How to use container queries

To use container queries, you must first define a container-type and optionally a container-name.

The container-type can have a value of size, inline-size, or normal.

  • size establishes a query container for the inline and block dimensions as well as for style (which we cover at the end of this article). 
  • inline-size establishes a query container for the inline dimensions as well as for style. You’ll likely use this 99% of the time.
  • normal establishes a query container only for style.

One potential gotcha is that if you use container-type: size you need to add an explicit height. It will ignore the height of children elements. This is how it is specced to behave.

Most often, using container-type: inline-size probably makes the most sense.

The container-name is a value of the <custom-indent> type (essentially some name you make up).

You can also use the container shorthand to define both properties. Such as:

.my-component {
  container: my-component / inline-size;
}

When using a container query or container query unit (which we will cover more in later sections), it will reference the nearest container in its ancestry tree unless you specify a particular container by including the container-name.

Once you’ve defined a container, you can use a @container query and select any descendant elements inside of it. For example:

@container (min-width: 500px) {
  .my-component p {
    font-size: 1.5rem;
  }
}

Or, if you want to use the container name in the query:

@container my-component (min-width: 500px) {
  .my-component p {
    font-size: 1.5rem;
  }
}

Note that you cannot style the element that is being queried inside of the container query itself (like .my-component {} in this case). But you can use it as a part of a more complex selector as seen above.

But you don’t have to refer to the container element in the selector, meaning this is also valid:

@container my-component (min-width: 500px) {
  p {
    font-size: 1.5rem;
  }
}

You can also use nesting.

.my-component {
  @container (min-width: 500px) {
    p {
      font-size: 1.5rem;
    }
  }
}

orientation and aspect-ratio

Instead of using explicit container sizes for container queries, we can also make use of orientation and its more generic form, aspect-ratio.

For example, here’s a Pen where we have the image on the left for larger screens and on top for smaller screens (a non-aspect ratio version of this sort of thing is in the section below).

When using aspect-ratio, remember that it’s width divided by the height, so aspect-ratio < 1/1 would be when the width is larger than the height (this example is equivalent to orientation: landscape). You can also use min-aspect-ratio or max-aspect-ratio instead of plain aspect-ratio and a comparison symbol.

Note that orientation and aspect-ratio can only be used with a container-type of size because it uses the container’s width and height. Setting a height is not typically a great idea for any template-based design where content can change.

What are container query units?

Container query units are an addition to the container query specification that provides units based on the container’s dimensions. This is handy for sizing pieces of a component based on the component’s container size.

What’s more, you’re not restricted to using container query units inside of container queries. You can use them anywhere a container is specified! That means that in some cases you can get away with just setting a property’s value to something that uses a container query unit and just leave it at that.

A shortened name for container query units?

“Container query units” is kind of a mouthful to say. Given that they can be used outside of container queries (so long as a container is defined), I think we can refer to these as “container units” like Chris Coyier did when he wrote about them a while back. I’m going to call them that for the rest of this article.

Available container units

Here’s the list of container units we currently have access to:

  • cqw: 1% of a query container’s width
  • cqh: 1% of a query container’s height
  • cqi: 1% of a query container’s inline size
  • cqb: 1% of a query container’s block size
  • cqmin: The smaller value of either cqi or cqb
  • cqmax: The larger value of either cqi or cqb

The width and height values are pretty straightforward to use. However, keep in mind that cqh will only use a container height if the container has a container-type of size. If inline-size is used, it will base its height on the nearest container with container-type: size, which might be the viewport.

Of these units, cqi will probably be the most commonly used unit for those who want to build websites for international audiences. For horizontal languages, it is equivalent to cqw. But it automatically switches to use cqh for vertical languages.

If you’re still not sure what inline means vs block here, maybe spend more time in the section above.

Use cases for container queries and container units

Let’s take a quick look at some use cases for container queries and container units!

Changing a component’s layout based on how much space is available

Perhaps the most common use case for container queries is to change the layout of a component’s contents based on the container’s size. Paired with ways of doing layouts like flex and grid, it can make creating pages that respond to different viewport sizes even easier.

Accessibility note: It’s best to keep the logical order of elements in the markup.

Taken to an extreme, you can make HTML and CSS components function kinda like an SVG like Dan Christofi did:

Adding non-vital detail when there’s more space available

In addition to changing the layout, sometimes it makes sense to hide some of the less important information or decorative elements when a component is smaller.

A great example of this is Chris Coyier’s calendar layout demo, where the vital parts of the calendar are kept for the smallest size but the rest is hidden:

(You may want to open this one full screen to have play.)

Fluid typography

Fluid typography is the concept of defining font sizes in a way where the type automatically scales based on some dimension between pre-defined bounds. In the past this has been based on the viewport width, but container query units make this concept a lot more powerful!

Check out this demo by Chris Coyier where you can drag to divvy up width between two elements, both with responsive type sizes:

Stephanie Eckles wrote a more in-depth article about using container query units for typography that I highly recommend!

When to use media queries instead

Content queries and units free us up from having to always use breakpoints that are tied to the layout. However, there are cases where you want content to update based on the layout! That’s when you should still use media queries—so content can be updated across multiple components at the same time.

Another time to use media queries is when you’re wanting to check certain device features, such as @media (not(hover)) { ... } or @media (not (color)) { ... } (which checks if the display is monochrome).

Browser support and style queries

Container queries for sizing have pretty solid browser support these days, as do container units.

There’s also discussion around creating style container queries. This would make certain things easier, like alternating between nested italic and normal text. Since the values of CSS variables can also be used in style queries, they could also be used as a more legitimate alternative to the CSS variable/custom property toggle hack. But at the moment they are only partially supported in WebKit-based browsers.

Conclusion

Container queries and container units enable us to create more isolated components. This makes it easier for components to be used across multiple pages, layouts, and systems. They’re prime for use in design systems!

If you’re interested in what other new CSS features I used when recreating my blog, check out my blog post about the process.

Bonus demo

This demo by SitePoint shows responsive layout paired with container queries to inspire you further!

]]>
https://frontendmasters.com/blog/container-queries-and-units/feed/ 0 282