Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have images of equal aspect ratios (300px x 255px) in divs taking up ~31% of the width to make 3 columns on desktop/tablet, then full width on mobile. The images scale to 100% within the div, with the height set as auto. I need to change them from img tags to background images

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;
}

Is there a way to make these images background images, and still have the aspect ratio dictate the height of the div--allowing the same responsive scaling? I'm hoping there's a way to do this without using .js, if possible. Can it be done with just CSS? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
876 views
Welcome To Ask or Share your Answers For Others

1 Answer

You could use % to set a padding taking width for reference to keep ratio. example : http://codepen.io/anon/pen/vNXgJp or http://codepen.io/anon/pen/VvKPMM (demos below)

.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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...