get auto generated `aspect-ratio` value in CSS?
Is there a way to get the auto generated value created by
aspect-ratio in CSS? I know I can pull this from computed with JS but it seems like there should be a way to do this in CSS?5 Replies
What value is created by aspect-ratio? Are you referring to the width and height? You can get those with container queries.
If you are referring to the ratio itself, the question doesn't make sense. You give the ratio when you specify it, so you already know it.
the way aspect-ratio works is that you, for example, set a
width: 400px and then add aspect-ratio: 4/3;. This automatically generates the height value for you. In this case it's easy that would be 300px.
My question is: is there anyway to access the auto generated height value in CSS? Can you set it to a var for reuse? My use case is I'd like to reuse it in a mask. It doesn't appear that you can just use aspect-ratio in mask-size or background-size like you can with width and height.I don't believe that this is possible with CSS alone.
I am not 100% sure of you actually want to do but maybe you could set the aspect ratio as a custom property and then calculate the mask height, something like this:
Sorry if I am miss-understanding the need/issue.
with
container-type: size you can get width and height as unitless numbers with the tan(atan2()) trick, and thus also the computed aspect-ratio https://codepen.io/Oddbj-rn-vernes/pen/raxVKPL
Not sure it it helps in your case π€·this is something I recently did in order to have a variable for height, skipped using
aspect-ratio in my case out of the need to know what the actual height was:
main's parent had a container-type: inline-size; in order to establish a container so that I can use cqw on main.
pretty similar to what @Chris is proposing but for my case I needed to work with a grid.
@Restemat problem with using container-type: size is that now your container need to be specific about block size since its content won't autoflow. It's an interesting idea tho.