Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I program the div height to be a certain percentage of it's current width? [duplicate]

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

like image 661
Bart Avatar asked Dec 12 '14 18:12

Bart


People also ask

Can I set height in percentage CSS?

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.

How do I resize a div proportionally?

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!

How do I make a div auto adjust width?

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.


1 Answers

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;
}
like image 151
LcSalazar Avatar answered Oct 27 '22 11:10

LcSalazar