Monday, April 29, 2024
HomeCSSAn Interactive Information to CSS Container Queries

An Interactive Information to CSS Container Queries


Introduction

Ah, container queries – a subject I explored three years in the past. It’s really satisfying to revisit it as soon as extra, this time with a deeper and extra complete strategy.

On this interactive information to container queries, I’ll clarify the issues they clear up, how they work, and the way we are able to use them right this moment in our workflows.

What’s the downside CSS container queries clear up?

Whereas constructing layouts in CSS, we all the time needed a technique to change a particular UI primarily based on the width of its container, not the viewport. Consequently, we have a tendency to make use of media queries for stuff that’s associated to the container, not the viewport.

Within the following instance, we now have a web page header that accommodates:

  • Order quantity
  • Actions: search and filter

When there isn’t a house, I wish to conceal the label from the search and filter actions. In media queries, we are able to do it like so:

@media (min-width: 580px) {
  
  .search {
    width: 32px;
    peak: 32px;
  }

  .search-label,
  .filter-label {
    show: block;
  }
}

Attempt to resize the browser beneath and spot how the search and filter label is hidden when the viewport width is lower than 580px.

card title

card desc in right here

card title

card desc in right here

card title

card desc in right here

card title

card desc in right here

card title

card desc in right here

The draw back of utilizing a media question is that the container will get greater when the sidebar is hidden. On this case, it’s extra logical to indicate the search and filter of their bigger measurement.

See the next, there may be sufficient house, however the search and filter are collapsed resulting from using a media question.

card title

card desc in right here

card title

card desc in right here

card title

card desc in right here

card title

card desc in right here

card title

card desc in right here

Utilizing CSS container queries

When utilizing a container question, we are able to fine-tune such particulars and provides the elements the power to increase primarily based on their container width, not the viewport.

To make use of container queries, we have to outline the container sort. The container identify is optionally available.

.important {
  container-name: important;
  container-type: inline-size;
}

As soon as outlined, we are able to use the container question similar to a media question. Right here, I’m exhibiting the <span> provided that the width is 370px or extra.

@container important (min-width: 370px) {
  .search-label,
  .filter-label {
    show: block;
  }
}

First, we have to outline a container in the principle part. Second, we are able to use @container with the kid parts we want (search and filter actions).

Play with it your self within the following demo by resizing the browser window.

card title

card desc in right here

card title

card desc in right here

card title

card desc in right here

card title

card desc in right here

card title

card desc in right here

@media (min-width: 580px) {

.search-label,

.filter-label {

show: block;

}

.search {

flex: 1;

}

}

@container card (min-width: 200px) {

.search-label,

.filter-label {

show: block;

}

.search {

flex: 1;

}

}

Attention-grabbing, proper? Let’s discover one other instance to ensure the issue container queries clear up is evident.

The cardboard element

The issue

We have now a listing of playing cards that change primarily based on the viewport width. To make it change primarily based on the viewport measurement, I used CSS grid minmax() perform.

.format {
  show: grid;
  grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));
  hole: 1rem;
}

Play with the demo (resize the browser window).

Easy methods to write CSS

New CSS options it is best to know

The primary concern I see is that the playing cards are too large when the viewport measurement is giant. Discover the ratio between the thumbnail and title sizes.

We will repair that by utilizing auto-fill within the CSS grid minmax() perform, however it should go away us with empty columns.

Easy methods to write CSS

New CSS options it is best to know

Not one of the best. Now we now have empty columns. What if, we wish to change the cardboard format to horizontal? We will try this.

@media (min-width: 800px) {
  .card {
    show: flex;
    align-items: begin;
  }
}

Attempt to change the viewport measurement. The cardboard will change from a stacked type to a horizontal one.

It really works as anticipated. Now, when the viewport measurement is above 800px, the cardboard type will change to horizontal.

However.. there’s a downside! What if we added extra playing cards? The horizontal type will look too condensed. This isn’t good.

Play with the next demo:

Discover that the horizontal type turned too condensed, it’s because we used a media question. When utilizing a media question, the browser doesn’t care about what’s going to occur to the elements if the obtainable house isn’t sufficient.

The answer

CSS container queries permit us to question in opposition to the container of a component. Within the context of the earlier instance, we are able to change the type to horizontal provided that the cardboard’s container is giant sufficient.

Right here is the cardboard’s markup:

<div class="layout__item">
  <div class="card">
    <div class="card-thumb">
      <img src="thumb.jpg" alt="" />
    </div>
    <div class="card-content">
      <h3>Card title in right here</h3>
    </div>
  </div>
</div>

In CSS, we have to outline the container sort. We will additionally outline the identify (not necessary however advisable).

.layout__item {
  container-type: inline-size;
  container-name: card;
}

We will use it like this:

@container card (min-width: 180px) {
  .card {
    show: flex;
    hole: 1rem;
    define: dotted 2px deeppink;
  }
}

Within the following interactive demo, you’ll be able to attempt the next:

  • Add extra or take away playing cards.
  • Select between media or container question.
  • Resize the browser window.
  • See the present CSS that’s utilized primarily based on the chosen question sort.

Easy methods to write CSS

New CSS options

CSS flexbox information

CSS grid information

@media (min-width: 800px) {

.card {

show: flex;

}

}

@container card (min-width: 200px) {

.card {

show: flex;

}

}

As you’ve seen utilizing a media question to alter the cardboard type isn’t logical on this case. The variety of playing cards can enhance or lower and that can have an effect on the cardboard’s content material.

CSS container queries will assist us to resolve that downside by offering us with a technique to question in opposition to the container.

Container question syntax

The container sort

The default worth for container-type is regular. To make use of a container question, we have to use inline-size as a price.

.important {
  container-type: inline-size;
}

We will then question parts which can be throughout the .important container, right here is an instance:

.part {
  @container (min-width: 700px) {
    
  }
}

Each container is a method container by default except we modify the container-type to inline-size.

The container identify

What occurs if we now have multiple container, how will we goal them? Nicely, that’s why we now have container-name. We will identify a container and name it when used.

.important {
  container-type: inline-size;
  container-name: important;
}

.part {
  @container important (min-width: 700px) {
    
  }
}

Dimension container queries shorthand

We will use the shorthand model so as to add the container identify and sort. It’s helpful if you happen to desire a neater scanning of the identify and sort.

.important {
  container: important / inline-size;
}

Fashion queries syntax

CSS type container queries permit us to question a CSS variable and do customized styling primarily based on that. It’s at present supported in Chrome and Safari Know-how Preview solely, but it surely’s value mentioning and explaining on this information.

By default, each factor is a method question. To make use of it, we are able to question a CSS variable on a dad or mum factor and write customized CSS that can apply to its little one parts.

.article-wrapper {
  --featured: true;
}

.article {
  @container type(--featured: true) {
    
  }
}

I’ll share a number of use instances later within the information.

Now that you recognize what the issue container queries clear up and the way the syntax works, let’s transfer to their frequent pitfalls.

Widespread pitfalls for container queries

A container can’t be sized by its contents

The container measurement ought to both be specific or come from a flex or a grid format. What does that imply? Let me present you an instance.

Within the following demo, we now have a web site header with a navigation.

<div class="header">
  <nav class="nav">
    <ul>
      
    </ul>
  </nav>
</div>

In CSS, I added the next:

.nav {
  container: nav / inline-size;
  show: flex;
  hole: 1rem;
  define: strong 1px;
}

Discover how the define is collapsed. When utilizing the inline-size containment, it will forestall the container from getting measurement data from its content material. Consequently, it should collapse to zero.

Attempt to toggle the “Stretch nav” button to see the repair.

To repair that, we have to drive the factor to fill the obtainable house in header.

.nav {
  flex: 1;
}

It’s not potential to question a container in opposition to itself

Let’s suppose that we now have a measurement container on a component. Sooner or later, we needed to type the container by querying the container itself.

.important {
  container: important / inline-size;
}

@container important (min-width: 700px) {
  background-color: #fefefe;
}

The background-color property received’t apply. This isn’t potential.

The container must be a further factor

Since we are able to’t question a container in opposition to itself, the container must be in a separate factor. In some instances, the extra factor is already there.

<div class="o-grid">
  <div class="o-grid__item">
    <article class="c-article">
      
    </article>
  </div>
</div>
.o-grid__item {
  container: card / inline-size;
}

.c-article {
  @container card (min-width: 500px) {
    
  }
}

Container question models

We used to make use of CSS viewport models to have a fluid typography, however the concern is, you guessed it, that it’s restricted to the viewport solely.

With CSS container queries, we are able to lastly use models which can be scoped to the container itself.

Within the following instance, I used question models to have a dynamic font measurement.

.author-name {
  font-size: clamp(14px, 10px + 1.33cqw, 20px);
}

font-size: clamp(14px, 10px + 1.33cqw, 20px);

Font measurement: 20

Ahmad Shadeed

Creator of Debugging CSS

As you’ve seen, we are able to use question models for font sizes. Nevertheless, the use instances aren’t restricted to that solely. We will use them for spacing (padding or margin) and extra.

In keeping with MDN, listed here are all of the question models we are able to use:

  • cqw: 1% of a question container’s width
  • cqh: 1% of a question container’s peak
  • cqi: 1% of a question container’s inline measurement
  • cqb: 1% of a question container’s block measurement
  • cqmin: The smaller worth of both cqi or cqb
  • cqmax: The bigger worth of both cqi or cqb

For me, I care concerning the cqw unit. I’ll use them within the upcoming use-cases part.

Container queries use instances

Container question demos are supported in all main browsers (Chrome 106+, Safari 16.0+, Firefox 110+).

Information part

One of the vital frequent use instances for container queries is the cardboard element. That may develop into useful when constructing featured information sections, for instance.

Within the following instance, we now have a information part with two important sections:

  • Left part: featured article with three articles beneath
  • Proper part: three articles and not using a thumb

We will use container queries for that:

  • Featured article
  • Switching from a stacked to a horizontal card and vice versa

With that, we are able to create a brand new element that adapts properly to the adjustments in its wrapper width.

See the next determine:

To make it extra clear, I created a simulation for breakpoints which you could see within the following interactive demo.

Play with the subsequent and former buttons, or click on on the rectangles and see the reason.

Default view.

Card title in right here

A little bit of desc textual content in right here. A little bit of desc textual content in right here.

Card title in right here

A little bit of desc textual content in right here. A little bit of desc textual content in right here.

Card title in right here

A little bit of desc textual content in right here. A little bit of desc textual content in right here.

Here’s a video for you that reveals the demo above, simply in case.

As you’ve seen, there are seven totally different breakpoints for this part. If we wish to use a media question for this, issues can get soiled shortly.

@media (min-width: 411px) {
  .card {
    
    flex-direction: row;
    hole: 1rem;
  }
}

@media (min-width: 431px) {
  .card--featured {
    
    flex-direction: row;
    hole: 1rem;
  }

  .card--featured .card-thumb {
    
  }
}

@media (min-width: 499px) {
  .card--featured {
    
    flex-direction: row;
    hole: 1rem;
  }

  .cards-list .card {
    
  }
}

@media (min-width: 554px) {
  .card--featured .card-thumb {
    
  }

  .cards-list .card {
    
  }
}

@media (min-width: 581px) {
  .card--featured .card-thumb {
    
  }
}

@media (min-width: 700px) {
  .cards-list .card {
    
  }
}

That is advanced and I didn’t even write all of the CSS, I simply added a pseudo-style code. With container queries, that is pretty straightforward. Let’s see how!

The cardboard element

The cardboard element has two states: stacked and horizontal. It should develop into horizontal if its container is wider by a particular quantity.

First, the cardboard must be wrapped in a container:

<div class="card-wrapper">
  <div class="card">
    
  </div>
</div>

Then, in CSS we write the next.

.card-wrapper {
  container: card / inline-size;
}

.card {
  
  show: flex;
  flex-direction: column;
  hole: 1rem;

  @container card (min-width: 250px) {
    flex-direction: row;

    .card-thumb {
      flex: 0 0 calc(2cqw + 80px);
    }
  }
}

So simple as that. We will add a number of spices in CSS, too.

For instance, I used a question unit within the calc() perform for the cardboard thumbnail. This is the same as “2 container question width”, which is 2% of the container’s width.

Card title in right here

A little bit of desc textual content in right here.

Card title in right here

A little bit of desc textual content in right here.

Right here is the cardboard element in an remoted demo. Attempt to resize the deal with in between the 2 variations.

It is a variation of the cardboard however with a bigger thumbnail and font sizes. I added the category card--featured to type it.

<div class="card-wrapper">
  <div class="card card--featured">
    
  </div>
</div>

In CSS:

.card--featured .card-thumb {
  @container card (min-width: 400px) {
    .cardThumb {
      flex: 0 0 calc(10cqw + 200px);
    }
  }
}

It’s value mentioning that in type container queries, we are able to add a CSS variable as a substitute of a CSS class.

<div class="card-wrapper">
  <div class="card " type="--featured: true;">
    
  </div>
</div>
@container card (min-width: 400px) and type(--featured: true) {
  .cardThumb {
    flex: 0 0 calc(10cqw + 200px);
  }
}

On the time of penning this information, type queries work in Google Chrome and are supported by default in Safari Know-how Preview.

Right here is the ultimate demo beneath. You may attempt the next:

  • Strive the “Auto resize” button and see the window develop.
  • Use the vary slider.
  • Take away a card and see what occurs.

Card title in right here

A little bit of desc textual content in right here. A little bit of desc textual content in right here.

Card title in right here

A little bit of desc textual content in right here. A little bit of desc textual content in right here.

Card title in right here

A little bit of desc textual content in right here. A little bit of desc textual content in right here.

Steps element

On this instance, we now have a steps element that should look otherwise primarily based on its container measurement. If the container is extensive, every step will appear like an arrow. If not, they’ll stack on high of one another.

Resize the window beneath and see how the element adjustments.

Overview

  1. Intro
  2. The way it works
  3. Overview

Overview

With the intention to end the information, you want to undergo the next steps.

  1. Intro
  2. The way it works
  3. Overview

Container queries make that easy.

.content material {
  container: steps / inline-size;
}

.steps__item {
  @container steps (min-width: 450px) {
    padding: 12px 8px 12px 18px;

    &:earlier than {
      --size: 2rem;
      font-size: 16px;
    }

    &:first-child {
      clip-path: polygon();
    }

    
  }
}

Social feed

I noticed this sample on Linkedin. When the viewport measurement is small, the motion buttons label is hidden on smaller sizes. It really works however shouldn’t be superb.

With media queries, this may be carried out however it should nonetheless be a hack.

.action-label {
  show: none;
}

@media (min-width: 500px) {
  .action-label {
    show: inline-flex;
  }
}

This can work, however the easiest change to the markup or the UI could cause it to fail. The reason being apparent as a result of we’re querying the viewport.

See the next demo:

Folks it’s possible you’ll know

😃The Joyful

🤩The Excited

🧐The Curious

When the viewport width is lower than 630px, the label is hidden.

Nevertheless, within the following case, the sidebar is hidden and the feed wrapper will get wider, however the label continues to be hidden.

Folks it’s possible you’ll know

😃The Joyful

🤩The Excited

🧐The Curious

That is the place container queries shine.

.action-label {
  @container content material (min-width: 470px) {
    show: block;
  }
}

Right here is the demo with container queries. Discover the state within the high left nook and see the way it adjustments primarily based on the container’s width. It’s magic, isn’t it?

Folks it’s possible you’ll know

😃The Joyful

🤩The Excited

🧐The Curious

Dashboard widgets: Instance 1

Oh, dashboard widgets. I suppose this can be a top-use instance for CSS container queries. In a dashboard, the person may need the power to customise the width or the scale of the columns.

Within the following instance, all of the widgets are the identical element however they modify otherwise primarily based on their container width.

Attempt to toggle between the grid and see it your self.

Cool, proper? There isn’t any magic in right here. I simply wrote three totally different types for a similar widget utilizing @container.

.widget {
  
  show: flex;
  align-items: middle;
  justify-content: space-between;

  
  @container column (max-width: 150px) {
    flex-direction: column;
    hole: 4px;
    background-color: #fff;
    padding: 5px;
    border-radius: 8px;
  }

  
  @container column (min-width: 250px) {
    flex-direction: column;
    align-items: begin;

    .icon {
      show: block;
      
    }
  }
}

Be happy to examine the demo above in case you wish to see all of the CSS particulars.

Dashboard widgets: Instance 2

On this instance, we now have a listing of stats that characterize some knowledge from a system. If a stats merchandise bought a wider container, I wish to change its design.

Right here is the CSS:

.widget {
  @container column (min-width: 280px) {
    flex-direction: row;
    align-items: middle;
    justify-content: space-between;
    background-color: #fff;

    h3 {
      font-size: 1.5rem;
    }

    p {
      font-size: 1.2rem;
    }
  }
}

Dashboard widgets: Instance 3

One other instance in a dashboard is a progress element. The element ought to adapt primarily based on its container width.

Attempt to toggle between “Grid 1” and “Grid 2”.

.progress {
  

  @container column (min-width: 250px) {
    flex-direction: column;
    align-items: begin;
    hole: 0.5rem;

    .proportion {
      show: block;
    }

    .progressWrapper {
      flex: auto;
      width: 100%;
      max-width: none;
    }

    .progress {
      peak: 10px;
    }

    .proportion {
      font-size: 16px;
    }
  }
}

Choices listing

On this instance, we now have a listing of choices that the person can select from. By default, each the icon and the label are in a brand new line. If there may be sufficient house, the icon and label will likely be subsequent to one another.

Play with the demo beneath:

  • Attempt to take away or add objects (max is 5)
  • Verify the “Auto resize” button or the vary slider

What’s your favourite meal?

Be happy to pick out a number of objects.

Right here is the CSS. So simple as that.

.option-wrapper {
  container: possibility / inline-size;
}

.possibility {
  @container possibility (min-width: 150px) {
    flex-direction: row;
    align-items: middle;
  }
}

You could be contemplating utilizing flex-wrap. Whereas it should work, we are able to’t management precisely when it should wrap, leading to some objects being wrapped whereas others aren’t.

Type inputs

On this instance, the shape inputs have a customized grid format that must be added if there may be sufficient house. With out container queries, this isn’t potential except we write a number of media queries.

See the breakpoints by clicking on the earlier and subsequent buttons.

Right here is the CSS wanted. By default, we now have a 1-col grid. If the container width is greater than 250px, the grid is modified.

.begin {
  show: grid;
  grid-template-columns: 1fr;
  hole: 1rem;

  @container part (min-width: 250px) {
    grid-template-columns: 1.55fr 1fr;
  }
}

Here’s a video of the earlier demo, in case you’re on cellular:

Threads listing

On this instance, we now have a thread element that should present otherwise primarily based on the container measurement. We will’t do it with media queries because it received’t work for all of the instances.

See the next determine:

To realize that, we are able to use container queries as beneath:

  • I used question models and CSS clamp to deal with the dynamic font measurement
  • I modified the flex-direction to row when there was sufficient house
.threadTitle {
  font-size: clamp(14px, 1cqw + 12px, 16px);
  font-weight: daring;
}

.threadMeta {
  font-size: clamp(13px, 1cqw + 11px, 15px);
  colour: #5b5b5b;
}

.thread {
  @container thread (min-width: 320px) {
    flex-direction: row;
    align-items: flex-start;
  }
}

Every question unit represents 1% of the container width.

Right here is the ultimate demo:

E-newsletter

A e-newsletter might be displayed in a small or a big house. We will accommodate that utilizing container queries.

<div class="newsletter-wrapper">
  <div class="e-newsletter">
    
  </div>
</div>
@container e-newsletter (inline-size < 250px) {
  h2 {
    
    &:earlier than {
      content material: "";
      show: block;
      peak: 4px;
      width: 60px;
      background-color: var(--brand-1);
    }
  }
}


@container e-newsletter (inline-size < 250px) {
  .form-group {
    place: relative;

    enter {
      padding-right: 32px;
    }

    button {
      place: absolute;
      proper: 4px;
      high: 8px;
      
    }

    svg {
      show: block;
    }
  }
}

Within the following demo, the e-newsletter has two variations primarily based on the container width. Attempt to resize the deal with between the 2 variations.

Subscribe to our e-newsletter

Get the newest tech information.

Subscribe to our e-newsletter

Get the newest tech information.

Timeline

On this instance, the timeline element adjustments its format primarily based on the obtainable house. The timeline can work in slim and extensive containers.

What you see beneath is similar element in several containers. On the left, we now have the straightforward model. On the precise, is the complete model.

Attempt to resize the demo beneath.

⚠️

Your browser does not help CSS type queries. You may check the demo in Chrome or Safari Know-how Preview.

Featured threads

  1. Assembly with Consumer

  2. Presentation

  3. Venture Kickoff

Newest threads

  1. Assembly with Consumer

  2. Presentation

  3. Venture Kickoff

Have you ever observed one other in-between variation? I created three variations for this element to work with totally different containers.

Here’s a simplified CSS:

@container timeline (inline-size > 300px) {
  .c-timeline__item {
    .c-timeline__content {
      padding-bottom: 3rem;
    }

    .c-timeline__content:after {
      left: calc(var(--size) / 2 * -1);
      width: var(--size);
      peak: var(--size);
    }
  }
}

@container timeline (inline-size > 430px) {
  .c-timeline {
    show: flex;
    justify-content: middle;
  }

  .c-timeline__item {
    --size: 40px;
    hole: 0;
    flex: 1;
    padding-left: 0;
    flex-direction: column;
    align-items: middle;
  }
}

A typical sample on the net is to increase or collapse a sidebar through a toggle button. We will use container queries to alter the format of the sidebar objects.

See the next instance and attempt to collapse the sidebar.

That is principally carried out with CSS container queries and Javascript was used to alter the sidebar width.

.apart {
  container: sidebar / inline-size;
}

.apart.collapsed {
  width: 50px;
}

.nav-item .label {
  opacity: 0;
  remodel: translateX(-5px);
  transition: 0.3s ease-out;

  @container sidebar (min-width: 100px) {
    opacity: 1;
    remodel: translateX(0);
  }
}

This won’t be the proper utilization for advanced sidebars, but it surely works properly for this easy utilization.

Occasion card

Whereas checking TechCrunch, I observed their implementation for the occasion card. It’s buggy and peculiar wanting so I considered why not giving it an opportunity with container queries.

Here’s a video of their design:

As you see, there are a few points:

  • Inconsistent measurement for the buttons.
  • Misaligned content material (e.g.: occasion title, location).
  • The UI wraps for objects with lengthy content material, making the others look odd.
  • No hole between content material. At sure breakpoints, the content material could be very shut to one another.

I truthfully don’t understand how that is nonetheless on TechCrunch. It’s filled with bugs!

Let’s have a look at the HTML.

<div class="event-card">
  <div class="meta">
    <p>Apr 25, 2024</p>
    <p>TechCrunch Early Stage 2024</p>
    <p>Boston</p>
  </div>
  <div class="actions">
    <a href="#" class="btn"> Purchase Tickets </a>
    <a href="#" class="btn ghost"> Be a sponsor </a>
  </div>
</div>

Every occasion card is wrapped inside an <li> which will likely be used as a container for every card.

<ul>
  <li class="card-wrapper">
    <div class="event-card">
      
    </div>
  </li>
  <li class="card-wrapper"></li>
  
</ul>

For the essential styling, the weather are stacked like the next instance:

We will use flexbox dynamic wrapping to indicate the buttons subsequent to one another when there may be sufficient house.

.btn {
  flex: 1 0 110px;
}

Meaning every button’s minimal width is 110px. If there may be not sufficient house, it should develop to fill its container.

Within the following variation, the viewport width is barely greater, and because of this, the buttons are displayed subsequent to one another.

Subsequent, I used @container to test if the container measurement is bigger than a particular worth. If sure, the cardboard’s content material will likely be displayed subsequent to one another.

.card-wrapper {
  container: occasion / inline-size;
}

@container occasion (min-width: 430px) {
  .event-card {
    show: flex;
    align-items: middle;
    hole: 1rem;
  }

  .meta {
    flex: 1;
  }
}

Cool. The following variation is the ultimate one, the place all of the content material is on the identical row. Consider it as a desk type. I did the next:

  • Modified the .meta to flex-direction: row
  • The date and site have a hard and fast width.
  • The title is fluid to the obtainable house
  • Reset the flex property for the buttons
@container occasion (min-width: 620px) {
  .meta {
    flex-direction: row;
    hole: 1.5rem;

    .title {
      flex: 1;
    }

    .date,
    .location {
      flex: 0 0 100px;
    }
  }

  .btn {
    flex: preliminary;
  }
}

See the outcome beneath and attempt to resize the window or play with the auto-resize button.

The story doesn’t finish right here. We used container queries to construct the cardboard element and now it really works no matter its container measurement.

In Github, the header part within the repository web page accommodates buttons and menus that change primarily based on the viewport width.

See the next video.

In the event you have a look at 0:11, discover how the apart is hidden and there may be more room, however among the particulars are hidden. On this particular case, container queries can repair that.

I attempted to recreate a mockup of the Github header so you’ll be able to play with it your self. Right here is the demo:

card title

card desc in right here

card title

card desc in right here

card title

card desc in right here

card title

card desc in right here

card title

card desc in right here

When the apart is hidden, the UI nonetheless has the identical view regardless that their container is now greater.

card title

card desc in right here

card title

card desc in right here

card title

card desc in right here

card title

card desc in right here

card title

card desc in right here

Right here is the CSS for the prototype above.

.meta {
  @container important (min-width: 330px) {
    show: flex;
  }
}

.menuButton {
  &.add {
    @container important (min-width: 330px) {
      show: flex;
    }

    @container important (max-width: 539px) {
      svg:first-of-type,
      span {
        show: none;
      }
    }

    @container important (min-width: 540px) {
      svg:last-of-type {
        show: none;
      }
    }
  }

  &.dots {
    @container important (min-width: 330px) {
      show: none;
    }
  }
}

.metaItem {
  span {
    @container important (min-width: 540px) {
      show: block;
    }
  }
}

.search {
  @container important (min-width: 330px) {
    show: flex;
  }

  @container important (max-width: 539px) {
    padding: 4px 10px;
    background: #f6f8fa;
    border: 1px strong #d0d7de;
    box-shadow:
      0px 1px 0px rgba(31, 35, 40, 0.04),
      inset 0px 1px 0px 1px rgba(255, 255, 255, 0.25);

    svg {
      show: none;
    }
  }

  @container important (min-width: 540px) {
    min-width: 160px;
    background: #fff;
    border: 2px strong #ececec;
  }
}

card title

card desc in right here

card title

card desc in right here

card title

card desc in right here

card title

card desc in right here

card title

card desc in right here

Fashion queries use instances

Please remember the fact that type queries are supported solely in Google Chrome and Safari Know-how Preview on the time of penning this information.

Dynamic timeline format

I explored an instance within the container queries the place we now have a timeline that adjustments primarily based on the container measurement. It really works, however there may be one downside. When the variety of timeline objects is 4 or extra, the complete variation will develop into weird-looking.

See the demo beneath:

Featured threads

  1. Assembly with Consumer

  2. Presentation

  3. Venture Kickoff

Newest threads

  1. Assembly with Consumer

  2. Presentation

  3. Venture Kickoff

  4. Code Overview

  5. Workforce Standup

  6. Assembly with Consumer

How we are able to repair that? We will test with CSS :has() if the variety of timeline objects is 5 or extra. If sure, we set a CSS variable --force-vertical: true.

.timelineWrapper {
  container: timeline / inline-size;
  --force-vertical: false;

  &:has(.c-timeline__item:nth-last-child(n + 5)) {
    --force-vertical: true;
  }
}

Then, we are able to mix the scale and elegance queries collectively to indicate the complete variation provided that the variety of objects is lower than 5 and have the minimal measurement wanted.

@container timeline (inline-size > 430px) and type(--force-vertical: false) {
  
}

Try it out beneath. Attempt to add extra objects and see what occurs. This demo works on the newest Chrome.

⚠️

Your browser does not help CSS type queries. You may check the demo in Chrome or Safari Know-how Preview.

Featured threads

  1. Assembly with Consumer

  2. Presentation

  3. Venture Kickoff

Newest threads

  1. Assembly with Consumer

  2. Presentation

  3. Venture Kickoff

If the browser you’re utilizing doesn’t help type queries, see the video beneath.

The fluid blockquote

A blockquote can reside in other places on an internet web page. For instance, it may be in a sidebar, article physique, full-width part, and extra.

We will change its type primarily based on the container width, however which may not be sufficient. We have to type it primarily based on the context, too.

To try this, we are able to set a customized CSS variable on the outer container.

<div class="content material" type="--context: article">
  <blockquote>
    
  </blockquote>
</div>

And in CSS, we are able to do the next:

@container type(--context: article) {
  blockquote {
    
  }
}

Let’s take a better look.

Article variation

This type is boxed, centered and designed to catch the person’s eye.

@container type(--context: article) {
  .articleQuote {
    background-color: lightcyan;
    padding: 1rem 0.5rem;
    text-align: middle;
    border-radius: 12px;
    max-width: 370px;
    margin: auto;

    &:earlier than {
      
    }
  }
}

⚠️

Your browser does not help CSS type queries. You may check the demo in Chrome or Safari Know-how Preview.

CSS is superior

some desc in right here

A blockquote can reside in other places on an internet web page. For instance, it may be in a sidebar, article physique, full-width part, and extra.

CSS container queries is nice. I like to recommend to offer it a attempt. It is helpful!

Ahmad Shadeed

A blockquote can reside in other places on an internet web page. For instance, it may be in a sidebar, article physique, full-width part, and extra.

We will change its type primarily based on the container width, however which may not be sufficient. We have to type it primarily based on the context, too.

Apart variation

A secondary content material that must be catchy, a easy one.

@container type(--context: apart) {
  .articleQuote {
    p {
      font-size: 15px;
    }

    cite {
      font-weight: daring;
      font-size: 13px;
    }
  }
}

⚠️

Your browser does not help CSS type queries. You may check the demo in Chrome or Safari Know-how Preview.

CSS container queries is nice. I like to recommend to offer it a attempt. It is helpful!

Ahmad Shadeed

It is a random paragraph only for the sake of this demo.

Full-width variation

A unique background colour and bigger font measurement. This is a vital quote and its type ought to replicate that.

.part:has(blockquote) {
  min-height: 180px;
  background-color: var(--brand-1);
}

@container type(--context: full) {
  .articleQuote {
    p,
    cite {
      colour: #fff;
    }

    p {
      font-size: clamp(1rem, 1rem + 2cqw, 1.35rem);
    }
  }
}

⚠️

Your browser does not help CSS type queries. You may check the demo in Chrome or Safari Know-how Preview.

It is a part in a web site.

CSS container queries is nice. I like to recommend to offer it a attempt. It is helpful!

Ahmad Shadeed

It is a part in a web site.

In case your browser doesn’t help type queries, here’s a video for reference.

Conditional horizontal article

An instance of the place type queries might be helpful is the power to alter a element primarily based on the context, not solely the container measurement.

See the next instance. We have now an apart with the part “Common articles”. If there’s a CSS variable --context: apart, I need the cardboard to show into the horizontal type if it’s throughout the measurement vary.

⚠️

Your browser does not help CSS type queries. You may check the demo in Chrome or Safari Know-how Preview.

Important information

Selfmade Lasagna Recipe

Straightforward Avocado Toast

Chocolate Lava Cake

Common articles

Spicy Thai Inexperienced Curry

Summer season Berry Salad

Hearty Beef Stew

<div class="part" type="--context: apart">

<div class="article">

</div>

</div>

To do the above, we are able to nest the scale question contained in the type question. That approach, the CSS will likely be utilized provided that

  • the container has the --context: apart
  • and the container measurement is between 170px and 485px
@container type(--context: apart) {
  @container (min-width: 170px) and (max-width: 485px) {
    .card {
      show: flex;
      align-items: middle;
      hole: 0.5rem;

      img {
        aspect-ratio: 4 /3;
        flex: 0 0 clamp(60px, 60px + 10cqw, 120px);
      }
    }
  }
}

Toggle a method question from one other

On this instance, we now have an article physique with a bit that accommodates associated articles. I wish to change the cardboard type from stacked to horizontal provided that it’s contained in the associated part.

⚠️

Your browser does not help CSS type queries. You may check the demo in Chrome or Safari Know-how Preview.

A blockquote can reside in other places on an internet web page. For instance, it may be in a sidebar, article physique, full-width part, and extra.

CSS container queries is nice. I like to recommend to offer it a attempt. It is helpful!

Ahmad Shadeed

A blockquote can reside in other places on an internet web page. For instance, it may be in a sidebar, article physique, full-width part, and extra.

We will change its type primarily based on the container width, however which may not be sufficient. We have to type it primarily based on the context, too.

<div class="part" type="--context: associated">

<div class="article">

</div>

</div>

Right here is the CSS:

  • First, we now have the type question for the horizontal type. It solely works if the --horizontal: true is added to the closest dad or mum.
  • Second, we test with one other type question concerning the --context: associated CSS variable. If it’s there, we swap the --horizontal: true one.

@container type(--horizontal: true) {
  .card {
    show: flex;
    align-items: middle;
    hole: 0.5rem;
    

    img {
      flex: 0 0 clamp(60px, 60px + 10cqw, 120px);
    }
  }
}


@container type(--context: associated) {
  --horizontal: true;
}

Attention-grabbing, proper? I discovered this utilization very helpful.

It’s value mentioning that Chrome helps container queries in DevTools. Within the following determine, I’m hovering over a component that’s displayed through a container question.

I’d have appreciated this extra if the double arrow icon is correctly aligned.

Assets

Outro

CSS container queries assist us to write down a very fluid elements that change primarily based on their container measurement. Within the subsequent few years, we’ll see much less media queries and extra container queries. After all, utilizing media queries will nonetheless be helpful for basic format stuff.

I hope you realized one thing new within the information. Thanks for studying.

Loved the learn? If you would like to help my work,
think about shopping for me a espresso. Every article takes about 50
cups to create. Thanks a latte!

Support me on Ko-fi

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments