0
0
SASSmarkup~5 mins

Container query preparation in SASS

Choose your learning style9 modes available
Introduction

Container queries let you style elements based on their container size, not just the screen size. Preparing your Sass code helps you write these queries clearly and reuse styles easily.

You want a card component to change layout depending on its container width.
You need buttons to adjust size inside different sidebar widths.
You want images to resize based on the box they are placed in, not the whole page.
You are building reusable components that adapt to different container sizes.
You want to avoid writing the same styles multiple times for different container sizes.
Syntax
SASS
@container (min-width: 30rem) {
  // styles here
}
Use @container followed by a condition like (min-width: 30rem) to start a container query.
Inside the block, write styles that apply when the container matches the condition.
Examples
This changes the background color of .box when its container is at least 40rem wide.
SASS
@container (min-width: 40rem) {
  .box {
    background-color: lightblue;
  }
}
This makes text smaller when the container is narrow.
SASS
@container (max-width: 20rem) {
  .text {
    font-size: 0.8rem;
  }
}
Using a Sass variable to set the container query breakpoint makes it easy to change later.
SASS
$container-breakpoint: 50rem;

@container (min-width: #{$container-breakpoint}) {
  .card {
    padding: 2rem;
  }
}
Sample Program

This example shows a container with a fixed width of 40rem. The .box inside changes its background color to light green when the container is at least 30rem wide.

SASS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Container Query Example</title>
  <style>
    .container {
      container-type: inline-size;
      border: 2px solid #333;
      padding: 1rem;
      width: 40rem;
      margin: 1rem auto;
    }
    .box {
      background-color: lightgray;
      padding: 1rem;
      transition: background-color 0.3s ease;
    }
    @container (min-width: 30rem) {
      .box {
        background-color: lightgreen;
      }
    }
  </style>
</head>
<body>
  <section class="container">
    <div class="box">This box changes color based on container width.</div>
  </section>
</body>
</html>
OutputSuccess
Important Notes

Remember to set container-type on the container element to enable container queries.

Use rem units for breakpoints to keep sizes consistent with user settings.

Container queries work only in browsers that support them; check browser compatibility.

Summary

Container queries let you style elements based on their container size.

Use @container in Sass to write container queries clearly.

Set container-type on containers to activate container queries.