Search code examples
csscss-calc

Is there a way to use use the width of self in a CSS calc rule?


I have already read Maintain the aspect ratio of a div with CSS (not a duplicate, please read further) and the other ways to do it, but here I'm asking something more specific:

Is there a way to use the width of the current element (self) in a CSS calc rule?

Or if not, is it possible to use the width of the parent element in a height: calc(...)?

Something like:

#container { 
    display: flex; 
    width: 500px; 
    flex-direction: row; 
}
#a { 
    background-color: red; 
    width: 50%;
}
#b { 
    background-color: blue; 
    width: 50%;
    height: calc(100% of self current width); /* <------- pseudo code here - does this exist? */
}
<div id="container">
<div id="a">
Hello
</div>
<div id="b">
World
</div>
</div>


Solution

  • You can use padding-top: 100%; to make width:height = 1:1.

    Reference: https://www.w3schools.com/howto/howto_css_aspect_ratio.asp