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

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

上代码

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

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

效果:

原理:

这是一个css小技巧:

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

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

complete.

posted @ 2020-05-10 19:47  海客无心x  阅读(1740)  评论(0编辑  收藏  举报