Search code examples
cssmedia-queriescontainer-queries

Can media queries resize based on a div element instead of the screen?


I would like to use media queries to resize elements based on the size of a div element they are in. I cannot use the screen size as the div is just used like a widget within the webpage, and its size can vary.


Solution

  • The original question asks about media queries as they were the only way to "query" a document at the time. Today, after a decade of work by the CSS Working Group and the community, we now have what's known as container queries, described in the CSS Containment Module, which do exactly what is described: apply styles to an element based on another element's containment styles. Djave has updated their answer to add usage examples. You can check browser support here.

    You can read more about how the updated specification was put together, including proposals, proofs-of-concept, discussions and other contributions by the broader web developer community here. For even more details and examples, check out Miriam Suzanne's extensive explainer.

    The following paragraphs were written before container queries were added, but still serve to explain why media queries aren't/weren't the tool for the job and why a new feature had to be created in the first place, and offer insight into the workarounds we used to have to make do with.


    Media queries aren't designed to work based on elements in a page. They are designed to work based on devices or media types (hence why they are called media queries). width, height, and other dimension-based media features all refer to the dimensions of either the viewport or the device's screen in screen-based media. They cannot be used to refer to a certain element on a page.

    If you need to apply styles depending on the size of a certain div element on your page, you'll have to use JavaScript to observe changes in the size of that div element instead of media queries.

    Alternatively, with more modern layout techniques introduced since the original publication of this answer such as flexbox and standards such as custom properties, you may not need media or element queries after all. Djave provides an example.