1

我在 div 中具有相等纵横比(300 像素 x 255 像素)的图像,占宽度的 31%,在桌面/平板电脑上制作 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 完成吗?谢谢!

4

2 回答 2

3

您可以使用 % 设置填充宽度以供参考以保持比率。示例: http ://codepen.io/anon/pen/vNXgJp 或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>

于 2015-09-23T17:22:02.737 回答
1

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

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;
}
于 2015-09-23T17:28:05.387 回答