具有 CSS 背景图片的纵横比 div

Aspect ratio divs with CSS background images

我在 div 中有等长宽比 (300px x 255px) 的图像,占据宽度的 ~31%,在 desktop/tablet 上形成 3 列,然后在移动设备上占据全宽。图片在 div 内缩放为 100%,高度设置为自动。我需要将它们从 img 标签更改为背景图片

http://codepen.io/anon/pen/yYagJd

**HTML:**
<div class="hotels">
    <img src="http://www.telodesign.com/test/cavallo-300.jpg" alt=""><br>
Here's a title
</div>

<div class="hotels">
    <img src="http://www.telodesign.com/test/cavallo-300.jpg" alt=""><br>
Here's a title
</div>

<div class="hotels">
    <img src="http://www.telodesign.com/test/cavallo-300.jpg" alt=""><br>
Here's a title
</div>

**CSS:**
.hotels {
    display: inline-block;
    width: 31.8%;
    vertical-align: top;
    margin-bottom: 22px;

}

*emphasized text*.hotels img {
    width: 100%;
    height: auto;
}

有没有办法让这些图像成为背景图像,并且仍然让宽高比决定 div 的高度——允许相同的响应缩放?如果可能的话,我希望有一种方法可以在不使用 .js 的情况下做到这一点。只用 CSS 就可以吗?谢谢!

你可以用%来设置一个padding取宽度作为参考保持比例。 例子 : http://codepen.io/anon/pen/vNXgJp or http://codepen.io/anon/pen/VvKPMM(下方演示)

.hotels {
  display: inline-block;
  width: 31.8%;
  vertical-align: top;
  margin-bottom: 22px;
  background: url(http://www.telodesign.com/test/cavallo-300.jpg) no-repeat red;
  background-size: 100% auto;
}
.hotels:before {
  content: '';
  padding-top: 85%;
  float: left;
}
<div class="hotels">
  Here's a title</div>

<div class="hotels">
  Here's a title</div>

<div class="hotels">
  Here's a title</div>

.hotels {
  display: inline-block;
  width: 31.8%;
  vertical-align: top;
  margin-bottom: 22px;
  background: url(http://www.telodesign.com/test/cavallo-300.jpg) no-repeat red;
  background-size: 100% auto;
}
.hotels:before {
  content: '';
  padding-top: 85%;
  display: inline-block;
  vertical-align: bottom;
  margin-left: -0.25em;
}
p {
  display: inline-block;
  width: 100%;
  text-align: center;
  background: rgba(0, 0, 0, 0.5);
  margin: 0;
  padding: 1em;
  box-sizing: border-box;
}
<div class="hotels">
  <p>Here's a title</p>
</div>

<div class="hotels">
  Here's a title</div>

<div class="hotels">
  Here's a title</div>

您可以尝试使用视图宽度来保持调整大小时的比例:

HTML
<div class="hotels">
Here's a title</div>

<div class="hotels">
Here's a title</div>

<div class="hotels">
Here's a title</div>

CSS

.hotels {
  display: inline-block;
  width: 31.8vw;
  height: 26.3vw;
  vertical-align: top;
    margin-bottom: 22px;
  background-image:url(http://www.telodesign.com/test/cavallo-300.jpg);
   background-size: cover;
}