Aspect ratio divs with CSS background images

前端 未结 2 713
独厮守ぢ
独厮守ぢ 2020-12-22 00:41

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

相关标签:
2条回答
  • 2020-12-22 01:24

    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>

    or

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

    0 讨论(0)
  • 2020-12-22 01:25

    You could try using view widths to keep the proportions on resize:

    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;
    }
    
    0 讨论(0)
提交回复
热议问题