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.
Looks like there is work being done on this now: https://github.com/ResponsiveImagesCG/cq-demos
The @media rule is used in media queries to apply different styles for different media types/devices. Media queries can be used to check many things, such as: width and height of the viewport. width and height of the device.
only screen: The only keyword is used to prevent older browsers that do not support media queries with media features from applying the specified styles.
In my experience, 320px, 768px, and 1200px are the most commonly used; these three values should be sufficient for targeting smart phones, tablets/laptops, and desktops, respectively.
The media query with the narrower max-width should fall later in the cascade than the media query with the wider max-width so it overrides properties assigned in the wider media query.
After nearly a decade of work — with proposals, proofs-of-concept, discussions and other contributions by the broader web developer community — the CSS Working Group has finally laid some of the groundwork needed for container queries to be written into a future edition of the CSS Containment spec! For more details on how such a feature might work and be used, check out Miriam Suzanne's extensive explainer.
Hopefully it won't be much longer before we see a robust cross-browser implementation of such a system. It's been a grueling wait, but I'm glad that it's no longer something we simply have to accept as an insurmountable limitation of CSS due to cyclic dependencies or infinite loops or what have you (these are still a potential issue in some aspects of the proposed design, but I have faith that the CSSWG will find a way).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With