119.css如何使图片固定为正方形

一次在商城项目中学到,产品说所有的商品缩略图都要展示正方形

上代码

众所周知,一个元素要为正方形, height = width 就可以了。可是,如果高度是不限定的呢?如何自适应的保持正方形呢?

<style>
  /* 这一段不必要 */
  html,body {
    height: 100%;
  }
  /* 以下是关键代码 */
  #wrap {
     50%;
    height: 100%;
    background: #089e8a;
  }
  #box {
     100%;
    height: 0;
    padding-bottom: 100%;
    position: relative;
    background: #74b1f4;
  }
  #box img {
    position: absolute;
     100%;
    height: 100%;
  }
</style>
</head>
<body>
  <div >
    <div ></div>
  </div>
</body>

效果:
119.css如何使图片固定为正方形
119.css如何使图片固定为正方形

原理:

这是一个css小技巧:

当 padding-bottom/padding-top/margin-top/margin-bottom 的值为百分比的时候:
计算结果是参照父元素的宽度。

  • 当我们设置height:0;padding-bottom:100%;
  • 元素的宽高就始终保持一致了。
  • width = height -> 正方形。

complete.