Using CSS Container Queries to Check an Element's Width and Respond Accordingly
CSS Container Queries allow responsive styling for an element's width rather than the viewport's width, as is the case with media queries.
This is useful for cases where, say, a collapsible sidebar changes a parallel container's width and the layout of the container needs to be different for narrow vs wide widths.
/* Define the container */
.container {
container-type: inline-size; /* or 'size' for both width and height */
container-name: my-container; /* optional name */
}
/* Query the container's width */
@container my-container (min-width: 400px) {
.child-element {
background: blue;
font-size: 1.2rem;
}
}
/* Or without a name (queries the nearest container) */
@container (max-width: 600px) {
.child-element {
background: red;
font-size: 0.9rem;
}
}
Tailwind CSS
As of Tailwind 4, container queries are built in in older versions, the @tailwindcss/container-queries
plugin is required
Markup:
Responds to container size!
Feedback?
Email us at enquiries@kinsa.cc.