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
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
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;
}
I use this
.aspect-ratio {
max-width: 100%;
}
.aspect-ratio:before {
content: '';
display: block;
width: 100%;
padding-bottom: ({height-aspect} / {width-aspect} * 100)%; // for 3 x 4, for instance: 75%
}
if you prefer less like me, you can make a mixin:
.aspectRatio(@widthAspect, @heightAspect) {
@aspect: @heightAspect/@widthAspect * 100;
max-width: 100%;
&:before {
content: '';
display: block;
width: 100%;
padding-bottom: ~"@{aspect}%";
}
}
If you set the top and bottom padding of an element in percentages it'll be relative to the width of the element.
When you use a percentage in height
, it is calculated with respect to the height of the generated box's containing block.
Since you want to calculate it with respect to it width, you can use, for example, padding-top
.
To avoid it affecting the contents, place them in a absolutely positioned wrapper.
#wrapper {
padding-top: 25%; /* ratio */
border: 1px solid;
position: relative;
}
#content {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
<div id="wrapper">
<div id="content">
<p>Foo</p>
<p>Bar</p>
<p>Baz</p>
</div>
</div>
Yes with jquery you can get the screen width and height, then you can target that div and set the heigth and width