Course contentsShow
← Web Development
Lesson 2656 of 2,98247. Data VisualizationFree lesson

Container Queries for Chart Layouts

Use container queries to adapt chart complexity and layout based on available space, not viewport.

Container Queries for Chart Layouts

You'll learn how to make charts adapt their complexity and layout based on their container's size, not the entire viewport.

The Problem with Viewport-Based Responsiveness

Traditional media queries respond to the browser window size, but your chart might live in a sidebar, modal, or grid cell that's much smaller than the viewport. A chart that looks great at "900px viewport" could be cramped in a 300px-wide sidebar on that same 900px screen.

Container queries solve this by letting elements respond to their parent container's size instead.

How Container Queries Work for Charts

First, mark the chart's parent as a query container:

.chart-wrapper {
  container-type: inline-size;
  container-name: chart;
}

Then write queries based on that container's width:

/* Simplified chart for narrow containers */
@container chart (max-width: 400px) {
  .chart-labels {
    font-size: 10px;
  }
  .chart-legend {
    display: none; /* Hide legend when cramped */
  }
  .data-point-label {
    display: none; /* Remove individual labels */
  }
}

/* Full-featured chart for wider containers */
@container chart (min-width: 600px) {
  .chart-labels {
    font-size: 14px;
  }
  .chart-grid {
    display: block; /* Show detailed gridlines */
  }
}

Think of it like adjustable Lego instructions: the same chart data builds different complexity levels depending on the space available in its box, not the whole room.

This is especially powerful for dashboard layouts where multiple charts share space—each adapts independently to its allocated area.

Key Takeaway: Container queries let charts intelligently simplify or enhance their visual complexity based on their immediate container size, creating truly modular, reusable data visualization components that work anywhere in your layout.