CSS Container Queries & Modern Layout in Practice: From Responsive to Component-Driven

前端工程

The Evolution of Responsive Design

CSS responsive design has evolved from media queries to container queries. Traditional @media relies on viewport width, while @container responds to parent container size, enabling truly self-contained responsive components.

Stage Technology Based On Limitation
Fixed Layout Fixed pixel widths None No adaptation
Media Queries @media Viewport width Components can't sense their container
Flexible Layout Flexbox / Grid Content-driven Can't switch layout by container
Container Queries @container Parent container size True component-level responsive

Container Queries Syntax

container-type Property

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

.sidebar-wrapper {
  container-type: size;
}

.scroll-wrapper {
  container-type: normal;
}
Value Meaning Queryable Dimensions
inline-size Enable inline-axis queries Width
size Enable both-axis queries Width + Height
normal Default, no queries None

container-name

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

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

Shorthand Syntax

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

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

@container Rules

@container card (min-width: 400px) {
  .card {
    display: grid;
    grid-template-columns: 200px 1fr;
    gap: 1rem;
  }
}

@container card (min-width: 200px) and (max-width: 399px) {
  .card {
    display: flex;
    flex-direction: column;
  }
}

@container sidebar (min-height: 500px) {
  .sidebar-nav {
    position: sticky;
    top: 1rem;
  }
}

Container Query Units

.card-title {
  font-size: clamp(1rem, 5cqi, 2rem);
  padding: 2cqi;
}

.card-body {
  margin-inline: 3cqi;
}
Unit Meaning
cqw 1% of container width
cqh 1% of container height
cqi 1% of container inline size
cqb 1% of container block size
cqmin min(cqi, cqb)
cqmax max(cqi, cqb)

Practical: Card Component

<div class="card-wrapper">
  <article class="card">
    <img class="card-image" src="photo.jpg" alt="Example" />
    <div class="card-content">
      <h3 class="card-title">Container Queries in Action</h3>
      <p class="card-desc">Automatically switch layout based on parent container width</p>
      <button class="card-btn">Learn More</button>
    </div>
  </article>
</div>
.card-wrapper {
  container: card / inline-size;
}

.card {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  padding: 1rem;
  border-radius: 12px;
  background: #fff;
  box-shadow: 0 2px 8px rgb(0 0 0 / 0.1);
}

.card-image {
  width: 100%;
  aspect-ratio: 16 / 9;
  object-fit: cover;
  border-radius: 8px;
}

@container card (min-width: 400px) {
  .card {
    display: grid;
    grid-template-columns: 200px 1fr;
    align-items: center;
  }

  .card-image {
    aspect-ratio: 1;
    border-radius: 12px;
  }

  .card-title {
    font-size: 1.25rem;
  }
}

@container card (min-width: 600px) {
  .card {
    grid-template-columns: 280px 1fr;
    padding: 1.5rem;
  }

  .card-title {
    font-size: 1.5rem;
  }
}

Practical: Sidebar Layout

.page-layout {
  display: grid;
  grid-template-columns: 1fr;
  gap: 1.5rem;
}

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

@container sidebar (min-width: 280px) {
  .sidebar-nav {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 0.5rem;
  }
}

@media (min-width: 768px) {
  .page-layout {
    grid-template-columns: 260px 1fr;
  }
}

Practical: Dashboard Widgets

.widget-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 1rem;
}

.widget {
  container: widget / inline-size;
  padding: 1rem;
  border-radius: 12px;
  background: #f8fafc;
}

@container widget (min-width: 350px) {
  .widget-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .widget-chart {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1rem;
  }
}

@container widget (max-width: 349px) {
  .widget-header {
    text-align: center;
  }

  .widget-chart {
    display: flex;
    flex-direction: column;
  }
}

CSS :has() Selector in Practice

.form-group:has(input:invalid) {
  border-color: #ef4444;
}

.form-group:has(input:invalid) .error-msg {
  display: block;
}

.card:has(img) {
  grid-template-rows: auto 1fr;
}

nav:has(.submenu:hover) .submenu {
  opacity: 1;
  visibility: visible;
}

details:has([open]) .arrow-icon {
  transform: rotate(180deg);
}

.fieldset:has(:focus) {
  box-shadow: 0 0 0 3px rgb(59 130 246 / 0.3);
}

CSS Native Nesting

.card {
  padding: 1rem;
  border-radius: 12px;

  & .card-title {
    font-size: 1.25rem;
    font-weight: 700;
  }

  & .card-body {
    margin-top: 0.5rem;

    & p {
      line-height: 1.6;
    }
  }

  &:hover {
    box-shadow: 0 4px 16px rgb(0 0 0 / 0.12);
  }

  @container card (min-width: 400px) {
    display: grid;
    grid-template-columns: 200px 1fr;
  }

  @media (prefers-color-scheme: dark) {
    background: #1e293b;
    color: #e2e8f0;
  }
}

Subgrid for Alignment

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 1.5rem;
}

.card {
  display: grid;
  grid-row: span 3;
  grid-template-rows: subgrid;
}

.card-title {
  font-size: 1.125rem;
}

.card-body {
  flex: 1;
}

.card-footer {
  margin-top: auto;
}

CSS Anchor Positioning

.tooltip-trigger {
  anchor-name: --trigger-anchor;
}

.tooltip {
  position-anchor: --trigger-anchor;
  position-area: top center;
  position-visibility: anchors-visible;
  padding: 0.5rem 0.75rem;
  background: #1e293b;
  color: #f8fafc;
  border-radius: 6px;
  font-size: 0.875rem;
}

.popover-menu {
  position-anchor: --trigger-anchor;
  position-area: bottom center;
  position-visibility: anchors-visible;
  margin-top: 4px;
  padding: 0.5rem 0;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgb(0 0 0 / 0.15);
}

View Transitions API

@view-transition {
  navigation: auto;
}

::view-transition-old(root) {
  animation: fade-out 0.2s ease-out;
}

::view-transition-new(root) {
  animation: fade-in 0.3s ease-in;
}

@keyframes fade-out {
  to { opacity: 0; transform: scale(0.98); }
}

@keyframes fade-in {
  from { opacity: 0; transform: scale(1.02); }
}

.card-image {
  view-transition-name: card-img;
}

::view-transition-old(card-img) {
  animation: shrink 0.3s ease-out;
}

::view-transition-new(card-img) {
  animation: grow 0.3s ease-in;
}
document.querySelector('.nav-link').addEventListener('click', async (e) => {
  e.preventDefault();
  const transition = document.startViewTransition(async () => {
    await updateContent(e.target.href);
  });
  await transition.finished;
});

Scroll-Driven Animations

.progress-bar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 3px;
  background: #3b82f6;
  transform-origin: left;
  animation: scale-x linear;
  animation-timeline: scroll();
}

@keyframes scale-x {
  from { transform: scaleX(0); }
  to { transform: scaleX(1); }
}

.reveal-item {
  opacity: 0;
  transform: translateY(30px);
  animation: reveal linear both;
  animation-timeline: view();
  animation-range: entry 0% entry 100%;
}

@keyframes reveal {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.parallax-bg {
  animation: parallax-move linear;
  animation-timeline: scroll();
}

@keyframes parallax-move {
  from { background-position-y: 0%; }
  to { background-position-y: 100%; }
}

Cascade Layers (@layer)

@layer reset, base, components, utilities;

@layer reset {
  *, *::before, *::after {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
  }
}

@layer base {
  body {
    font-family: system-ui, sans-serif;
    line-height: 1.6;
    color: #1e293b;
  }

  a {
    color: #3b82f6;
    text-decoration: none;
  }
}

@layer components {
  .btn {
    display: inline-flex;
    align-items: center;
    padding: 0.5rem 1rem;
    border-radius: 8px;
    font-weight: 500;
  }

  .btn-primary {
    background: #3b82f6;
    color: #fff;
  }
}

@layer utilities {
  .text-center { text-align: center; }
  .mt-4 { margin-top: 1rem; }
}

Modern CSS Reset

@layer reset {
  *, *::before, *::after {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
  }

  html {
    hanging-punctuation: first last;
  }

  body {
    min-height: 100dvh;
    line-height: 1.5;
    -webkit-font-smoothing: antialiased;
  }

  img, picture, video, canvas, svg {
    display: block;
    max-width: 100%;
  }

  input, button, textarea, select {
    font: inherit;
  }

  p, h1, h2, h3, h4, h5, h6 {
    overflow-wrap: break-word;
  }

  :root {
    color-scheme: light dark;
  }

  @media (prefers-reduced-motion: no-preference) {
    :has(:target) {
      scroll-behavior: smooth;
    }
  }
}

Logical Properties

.card {
  margin-block: 1rem;
  margin-inline: auto;
  padding-block: 1.5rem;
  padding-inline: 1rem;
  border-inline-start: 4px solid #3b82f6;
  inset-block-start: 0;
  inset-inline-start: 0;
  max-inline-size: 800px;
  block-size: auto;
}

.nav-link {
  margin-inline-end: 1rem;
  padding-block: 0.5rem;
  padding-inline: 1rem;
  border-block-end: 2px solid transparent;
}

.nav-link:hover {
  border-block-end-color: #3b82f6;
}
Physical Property Logical Property Description
margin-top margin-block-start Block direction start
margin-bottom margin-block-end Block direction end
margin-left margin-inline-start Inline direction start
margin-right margin-inline-end Inline direction end
width inline-size Inline dimension
height block-size Block dimension
top inset-block-start Block direction offset
left inset-inline-start Inline direction offset

Browser Support (2026)

Feature Chrome Firefox Safari Status
Container Queries 105+ 110+ 16+ ✅ Stable
Container Query Units 105+ 110+ 16+ ✅ Stable
:has() 105+ 121+ 15.4+ ✅ Stable
CSS Native Nesting 120+ 117+ 17.2+ ✅ Stable
Subgrid 117+ 71+ 16+ ✅ Stable
Anchor Positioning 125+ ⚠️ Experimental
View Transitions 111+ 18+ ⚠️ Partial
Scroll-driven Animations 115+ ⚠️ Experimental
@layer 99+ 97+ 15.4+ ✅ Stable
Logical Properties 69+ 66+ 12.1+ ✅ Stable

Progressive Enhancement Strategies

@supports (container-type: inline-size) {
  .card-wrapper {
    container: card / inline-size;
  }

  @container card (min-width: 400px) {
    .card {
      display: grid;
      grid-template-columns: 200px 1fr;
    }
  }
}

@supports not (container-type: inline-size) {
  @media (min-width: 768px) {
    .card {
      display: grid;
      grid-template-columns: 200px 1fr;
    }
  }
}
if (CSS.supports('container-type', 'inline-size')) {
  document.documentElement.classList.add('cq-supported');
}

Common Gotchas and Debugging

Gotcha 1: Forgetting container-type

.card-wrapper {
  container-name: card;
}

@container card (min-width: 400px) {
  .card { display: grid; }
}

You must also set container-type or use the shorthand container: card / inline-size.

Gotcha 2: Container cannot query itself

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

@container (min-width: 400px) {
  .card { display: grid; }
}

Container queries only affect descendants, not the element with container-type set on it.

Gotcha 3: Container size is 0

If the container has no explicit width (e.g., a flex child with width: fit-content), container queries may not work. Ensure the container has a determined size.

Debugging Tips

  • Chrome DevTools → Elements panel → look for @container markers
  • Use container-type: inline-size instead of size to avoid unnecessary layout calculations
  • Check if overflow: hidden affects size calculation

Performance Considerations

Concern Recommendation
Container count Avoid deeply nested containers, each adds query overhead
container-type Prefer inline-size, size triggers bidirectional calculation
Query breakpoints Keep to 3-5, avoid too many conditional branches
Reflow scope Container queries only affect subtree, smaller scope than media queries
:has() Avoid complex :has() selectors on large element sets
Scroll animations animation-timeline: scroll() is 10x+ faster than scroll event listeners
View Transitions Old/new snapshots consume memory, limit view-transition-name count on large pages

FAQ

Q: Can container queries replace media queries?

A: Not entirely. Page-level layouts (navbar, overall grid) still need @media, while component-level responsiveness uses @container. Use both together.

Q: What's the difference between container queries and Flexbox/Grid auto-sizing?

A: Flexbox/Grid are content-driven (fit what space is available), while container queries are condition-driven (switch to a different layout mode when space is sufficient).

Q: Does :has() affect performance?

A: Simple usage (e.g., :has(input:focus)) has minimal overhead. Avoid complex chained :has() selectors on thousands of elements.

Q: What's the difference between Subgrid and regular Grid?

A: Subgrid lets child grids inherit parent grid track definitions, enabling cross-card alignment. Regular Grid children are independent and can't align across items.

Q: When can I use Anchor Positioning?

A: As of 2026, Chrome 125+ supports it. Firefox and Safari are still implementing. For production, use libraries like Floating UI as a fallback.


Try these browser-local tools — no sign-up required →

#CSS#容器查询#现代布局#前端#教程