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.
Update
Looks like there is work being done on this now: https://github.com/ResponsiveImagesCG/cq-demos
No, 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 thatdiv
element instead of media queries.This is currently not possible with CSS alone as @BoltClock wrote in the accepted answer, but you can work around that by using JavaScript.
I created a container query (aka element query) prolyfill to solve this kind of issue. It works a bit different than other scripts, so you don’t have to edit the HTML code of your elements. All you have to do is include the script and use it in your CSS like so:
https://github.com/ausi/cq-prolyfill
The question is very vague. As BoltClock says, media queries only know the dimensions of the device. However, you can use media queries in combination with descender selectors to perform adjustments.
The only other solution requires JS.
I was also thinking of media queries, but then I found this:
Just create a wrapper
<div>
with a percentage value forpadding-bottom
, like this:It will result in a
<div>
with height equal to 75% of the width of its container (a 4:3 aspect ratio).This technique can also be coupled with media queries and a bit of ad hoc knowledge about page layout for even more finer-grained control.
It's enough for my needs. Which might be enough for your needs too.
The only way I can think that you can accomplish what you want purely with css, is to use a fluid container for your widget. If your container's width is a percentage of the screen then you can use media queries to style depending on your container's width, as you will now know for each screen's dimensions what is your container's dimensions. For example, let's say you decide to make your container's 50% of the screen width. Then for a screen width of 1200px you know that your container is 600px
I've just created a javascript shim to achieve this goal. Take a look if you want, it's a proof-of-concept, but take care: it's a early version and still needs some work.
https://github.com/marcj/css-element-queries