Aspect ratio divs with CSS background images

前端 未结 2 733
独厮守ぢ
独厮守ぢ 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;
    }
    Here's a title
    Here's a title
    Here's a title

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

    Here's a title

    Here's a title
    Here's a title

提交回复
热议问题