How to Set Child Height as Percentage of Parent Width

Hey everyone :wave: :smile:

Is there a way to set the height of an element as a percentage of the parent’s width?

I know you can use the percentage unit to set the child’s height relative to the parent’s height (e.g. height: 40%), but I’m looking for a way to set the child’s height relative to the parent’s width (or more generally, a child’s dimension relative to the parent’s other dimension).

Thank you!

You can accomplish by using padding-top inside the child, basically making height equal
to the width.

I’m not seeing how that would work. Could you provide an example please?

child{
padding-top: 100%
}

No, I get how to apply the padding or padding-top property. What I wasn’t getting is how it answers the question. I tried it, so now I understand what you mean, but it unfortunately has the side effect of changing height based on the content of the child element, which is not what I’m looking for. Thanks, though!

Do you mind a JavaScript solution?

Hey Nick :wave:

I know how to do it in JavaScript; I was hoping there was a way in pure CSS. Do you know of such a solution?

Hey, my friend. Umm, not really, no. I’ve had that problem before. Could you share a codepen or something I could fork? Sometimes it can be accomplished with CSS variables.

Hi there!
you can set the height of a child element based on it’s parent element’s width, using aspect-ratio property.

Example code

.parent {
width: 100%; /* Example parent width */
}

.child {
width: 50%; /* Example width /
aspect-ratio: 2 / 1; /
Height is half of the width /
background-color: lightblue; /
Just for visibility */
}

2 Likes

Good point! I don’t know why I didn’t think of that. I think that should work, thanks!

1 Like

It’s alright, I think the aspect-ratio solution Hassan suggested should work for my use case. Thanks, dude!

1 Like

Yep, aspect ratios will definitely do the trick. Thanks @hasanzaib1389 !

1 Like