Is it possible to give a div a width which is a percentage of the window, and a height which is a certain percentage of it's current width? So the div resizes, but keeps the same aspect ratio when you resize your browser window.
Thanks Ciao
CSS height and width Values length - Defines the height/width in px, cm, etc. % - Defines the height/width in percent of the containing block. initial - Sets the height/width to its default value. inherit - The height/width will be inherited from its parent value.
For proportional resizing purposes, it makes matters extremely simple: Define the width of an element as a percentage (eg: 100%) of the parent's width, then define the element's padding-top (or -bottom) as a percentage so that the height is the aspect ratio you need. And that's it!
Using width, max-width and margin: auto; Then, you can set the margins to auto, to horizontally center the element within its container. The element will take up the specified width, and the remaining space will be split equally between the two margins: This <div> element has a width of 500px, and margin set to auto.
There's the padding
trick, already answered, but I use another approach, envolving two nested divs.
The parent one, I set the width. The child one, I use the height
value as a container unit vw
- (means viewport width).
It works well, see here (resize the viewport)
<div>
<div></div>
</div>
CSS:
div {
width: 100%;
}
div > div {
background: silver;
height: 10vw;
}
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