12

Is it possible to proportionally scale a div like an img using only CSS? Here is my first attempt: http://dabblet.com/gist/1783363

Example

div {
 max-width:100px;
 max-height:50px;
}
img {
 max-width:100px;
 max-height:50px;
}

Actual Result

Container: 200 x 100
Div:       100 x 50
Image:     100 x 50

Container: 50  x 100
Div:       50  x 50  // I want this to be 50x25, like the image
Image:     50  x 25
0b10011
  • 18,397
  • 4
  • 65
  • 86
Adam Youngers
  • 6,421
  • 7
  • 38
  • 50

3 Answers3

37

Since vertical paddings set in percent are calculated out of width of an element we can make a div always be of a certain aspect ratio.

If we set padding-top:50%; height:0, the height of the div will always be half of its width. And to make text appear inside such a container you need to make it position:relative and put another div inside it and position it absolutely 10px away from all four sides (the padding you set first).

See my fork of your code.

Spadar Shut
  • 15,111
  • 5
  • 47
  • 54
  • genius! [filling character limit] – Dominic May 21 '12 at 10:44
  • 4
    If this doesn't work for anyone (it didn't for me), use padding-bottom instead of padding-top, as per this answer: http://stackoverflow.com/questions/8894506/can-i-scale-a-div-height-proportionally-to-width-of-the-div-with-the-help-of-onl – bradleygriffith Sep 03 '13 at 00:26
  • 1
    Unfortunately horizontal padding *also* uses the width, so this trick doesn't work with a percent height and padding-left. – Jackson May 28 '14 at 03:25
5

Sort of. You could use transformations to scale it up, but I'm not sure that's what you have in mind.

-webkit-transform:scale(2); (and other prefixes) would double it in size, without altering page layout.

zim2411
  • 628
  • 4
  • 6
0

Try:

.container img {
    height:50vw;
}

The vw follows the viewport You need to set in the head of your document:

<head>
<meta name="viewport" content="width=device-width">
</head>
user3849374
  • 127
  • 1
  • 3