宽高比div与CSS背景图片

时间:2015-09-23 17:08:16

标签: html css image responsive-design responsive-images

我在div中占有相同宽高比(300px x 255px)的图像占据宽度的约31%,在桌面/平板电脑上制作3列,然后在移动设备上制作全宽。 div中的图像缩放到100%,高度设置为auto。我需要将它们从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完成吗?谢谢!

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分: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;
}