This question already has an answer here:
- Maintain the aspect ratio of a div with CSS 21 answers
I have a responsive div
that contains a large amount of text and is the same width as its container.
<div>This is a long string of text, but the real text will be a lot longer.</div>
How can I force the div
to retain a height which is 50% of its width and stop the contents from overflowing the boundaries using only HTML and CSS?
It should look like this
And this
There is another way to perform this effect. You can use Viewport Units:
Updated JsFiddle
By using
vw
you are setting the element's height to a percentage according to the viewport's width.Downside:
This solution would only work however if your layout depends on the window's dimensions, as the result of viewport units will always vary according to the window's size.
So, if you use it, be sure to set both
width
andheight
to the desired percentage scale value.What is the CSS padding trick?
First some information about containing blocks for reference.
Now, here's the trick.
It is intuitive that horizontal padding percentages would reference the width of the containing block. However, vertical padding percentages also refer to the width, not the height.
What does that mean for maintaining aspect ratio?
What this means is that if you have an element which is the same width as its parent, and you set
padding-bottom: 50%
, the element will be half as wide as it is tall.However, if the element is less than the full width of its parent, because the padding property refers to the parents width the numbers will change.
For example, if the element is half the width of its parent and you set
padding-bottom: 50%
, it will be as tall as it is wide.This is because percentages for the padding property are relative to the containing block, not the element.
To make an element which is half its parent's width retain an aspect ratio of 2:1 (half as tall as it is wide), cut the percentage in half.
How can I use this in the real world?
If the element in question contains any content which takes up space in the document flow, the height will change. To avoid this you can take advantage of another CSS trick.
When an element is set to
position: absolute
it will be positioned in reference to its closest ancestor withposition: absolute
,position: relative
orposition: fixed
. If the element has no such ancestors, it will positioned in reference to the root element.This means, if you set
position: relative
on this new responsivediv
, you can insert a child withposition: absolute
and tell it to be the same size as the parent usingtop: 0; width: 100%; bottom: 0;
.To make sure the contents won't overflow the boundaries set
overflow: auto
This will create an element which retains its aspect ratio and can contain content without changing the aspect ratio.
See it in action!