CSS固定スケール画像

1235 ワード

Just create a wrapper  <div>  with a percentage value for  padding-bottom , like this:
div {
  width: 100%;
  padding-bottom: 75%;}

It will result in a  <div>  with height equal to 75% of the width of its container (a 4:3 aspect ratio).
This relies on the fact that for padding :
The percentage is calculated with respect to the width of the generated box's containing block [...] (source: w3.org, emphasis mine)
Padding-bottom values for other aspect ratios and 100% width :
aspect ratio  | padding-bottom value
--------------|----------------------
    16:9      |       56.25%
    4:3       |       75%
    3:2       |       66.66%
    8:5       |       62.5%

Placing content in the div :
In order to keep the aspect ratio of the div and prevent it's content from stretching it, you need to add an absolutely positioned child and stretch it to the edges of the wrapper with:
div.stretchy-wrapper {
  position: relative;}div.stretchy-wrapper > div {
  position: absolute;
  top: 0; bottom: 0; left: 0; right: 0;}

Here's a demo and another more in depth demo