There is a trick that allows you to do it very easily: when the padding
you define it with percentage values, the reference value is the width of the container. From the W3C website, on the CSS 2 specifications page :
The percentage is calculated with respect to the width of the
generated box with containing block, even for 'padding-top' and
'padding-bottom' If the containing block's width depends on this
element, then the resulting layout is undefined in CSS 2.2.
Translation and my bold type: The percentage is calculated with respect to the width of the box generated by the container block, even in the vertical values (padding-top and padding bottom). If the width of the container block depends on this element, then the result is undefined.
.ratio16-9 {
width: 100%;
padding-bottom: 56.25%; /* resultado de 9/16 */
background-color:gold;
}
#contenedor {
width:30%;
background-color: gray;
margin: 5px;
position:relative;
}
#main {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
<div id="contenedor">
<div class="ratio16-9"></div>
<div id="main">hola, este <pre>div</pre> es el contenedor interno
</div>
Now, the div 16/9 has a padding that occupies all the height, the content itself has a height of 0 pixels ... so if we put something, it will occupy some space and distort the div. The solution is that everything that is inside does not affect the size: instead of putting our content in this div, that all it does is give shape and size, we put it in another element that has absolute position.
Note : I think the correct solution will be based on the use of the property described above, but maybe my example (proof of concept) is not the cleanest. I put this answer as wiki so that anyone can add a better implementation.
To optimize the HTML code a bit and not have an empty div
we can also use the psudoelements ::after
or ::before
. On the other hand, having the content in div
with absolute position if it exceeds the size of the container will be out of this, to avoid it we put a overflow: auto;
that shows us a scroll when necessary.
#contenedor {
width: 40%;
background-color: gold;
margin: 5px;
position: relative;
overflow: auto;
}
#contenedor::after {
content: "";
display: block;
padding-bottom: 56.25%;
}
#main {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
<div id="contenedor">
<div id="main">Facilis quaerat et id est aut voluptates laboriosam velit. Saepe dignissimos aut impedit sit molestiae aut quibusdam. Earum quis ratione vitae quae sit assumenda officiis dolorem. Nesciunt labore nobis porro consectetur ut.</div>
</div>Facilis quaerat et id est aut voluptates laboriosam velit. Saepe dignissimos aut impedit sit molestiae aut quibusdam. Earum quis ratione vitae quae sit assumenda officiis dolorem. Nesciunt labore nobis porro consectetur ut.