Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I keep div a certain ratio, but give it a max size?

Tags:

html

css

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/

like image 362
Dori Avatar asked Nov 12 '13 15:11

Dori


People also ask

How do I keep my div aspect ratio?

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.

How do I make a div stay the same size?

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.

How do you maintain the aspect ratio of an image?

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.

How do I make a div not smaller than its contents?

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).


1 Answers

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

like image 145
Alex Guerrero Avatar answered Nov 15 '22 10:11

Alex Guerrero