I'm trying to keep a div
element a specific ratio (say, 1:2), but keep the width less than 200px.
What I've got so far:
div {
width: 100%;
height: 0;
padding-bottom: 50%;
max-width: 200px;
}
It doesn't work - if I expand the window, the width stops expanding at 200px but the height keeps growing!
I've tried setting box-sizing: border-box
and max-height: 100px
, but neither work.
What should I do?
Here's a fiddle: http://jsfiddle.net/WVu3s/
In the HTML, put the player <iframe> in a <div> container. In the CSS for the <div>, add a percentage value for padding-bottom and set the position to relative, this will maintain the aspect ratio of the container. The value of the padding determines the aspect ratio. ie 56.25% = 16:9.
if you set width:500px; and height:300px; (or whatever size you want) the div should stay the same size. Also, you can set overflow:hidden; so that if whatever is in the div goes beyond those bounds, it is not shown, and does not resize the div. Save this answer.
By setting the width property to 100%, you are telling the image to take up all the horizontal space that is available. With the height property set to auto, your image's height changes proportionally with the width to ensure the aspect ratio is maintained. The end result is an image that scales up or down perfectly.
You can simply use the CSS display property with the value inline-block to make a <div> not larger than its contents (i.e. only expand to as wide as its contents).
Here is a pure CSS solution based on the code from this post but with some minor changes:
HTML
<div class = "box">
<div class = "content">Ratio 1:2</div>
</div>
CSS
/* Box styles */
.box {
width: 100%;
position: relative;
display: inline-block;
max-width:200px; /* max width of the box */
}
.box:after {
padding-top: 50%; /*1:2 ratio*/
display: block;
content: '';
}
/* Style that should be applied to the box content */
.content {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
background-color: green;
}
And here is a demo
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