7

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/

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Dori
  • 1,035
  • 1
  • 12
  • 22
  • 1
    To maintain a given aspect ratio for elements in the general case, I know no other solution than JavaScript. – Denys Séguret Nov 12 '13 at 15:20
  • Take a look at this: http://stackoverflow.com/questions/12170261/how-to-auto-resize-a-div-with-css-while-keeping-aspect-ratio. You're on the right track, just missing a few elements for implementation of that method. That `padding-bottom` is reading from the page height, rather than its parent element. – Chad Nov 12 '13 at 15:43

2 Answers2

3

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

Community
  • 1
  • 1
Alex Guerrero
  • 2,109
  • 1
  • 19
  • 28
  • Thanks for the reply, but this doesn't address my max-width issue... the element's height will keep growing... unless I misread something – Dori Nov 13 '13 at 16:17
  • Yes, in the examples it shows a way to solve your `max-width` issue. anyway I've edited my original post with a new solution, the older solves the problem but this is better, here is a [demo](http://jsfiddle.net/WVu3s/9/) of the old version to compare – Alex Guerrero Nov 13 '13 at 18:12
0

In my situation the issue was that I wanted to display two different images depending on a css class applied to the body tag. I could have just used display:none on which one I wanted to not show, but that would involve loading both when only one was needed, so I ended up with this:

HTML:

<div class='arrow'>
    <img src="/img/arrow.png" style='max-width: 100%;'>
</div>

CSS:

.arrow {
  max-width: 100%;
  overflow: auto;
}

.darktheme .arrow {
  background: url(/img/arrow-darktheme.png) center no-repeat;
}
.darktheme .arrow img {
  opacity: 0;
}

It loads both under darktheme conditions, but only one if darktheme isn't applied.

MalcolmOcean
  • 2,807
  • 2
  • 29
  • 38