css 实现正方形自适应 并且内容居中

2023-06-14  本文已影响0人  南土酱

1.伪元素加 绝对定位实现

 <style>
  .square3 {
      width: 100%;
      overflow: hidden;
      background: #ccc;
      margin: 10px;
      position: relative;
  }
  .square3:after {
      content: '';
      display: block;
      margin-top: 100%; /* margin 百分比相对父元素宽度计算 */
  } 
  .square3 > .con{
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
    height: 30px;
  }
</style>  

 <div style="display: flex;">
    <div class="square3">
    <div class="con">sfasfffffffffffffffffffffffffffffffffffaa</div>
    </div> 
    <div class="square3">
        <div class="con">sdsd</div>
    </div>
     <div class="square3">
        <div class="con">gg</div>
      </div> 
 </div>

这个方法的缺点是 con这个元素的高度得固定,否则垂直居中不生效。而且只能单行显示。

多行显示版本: 主要修改square3 css 和 最外层 div 增加 flex-wrap:wrap ;

.square3 {
      width: calc((100% - 68px) / 3);
      min-width: calc((100% - 68px) / 3);
      max-width: calc((100% - 68px) / 3);
      overflow: hidden;
      background: #ccc;
      margin: 10px;
      position: relative;
  }
<div style="display: flex; flex-wrap:wrap ;"> 
  <div class="square3"> xxxx.....
   <div class="square3"> xxxx.....
   <div class="square3"> xxxx.....
</div>

这个方法又多一个小缺点 就是 calc 里边的 68px 得自己根据盒子的 padding + margin + border 去计算,得写死。然后 /3 代表每行固定显示3个

2 使用calc 加 padding

<div style="display: flex; flex-wrap:wrap ;"> 
  <div class="item"> 
  xxxx
  </div>
  <div class="item"> 
  xxxx
  </div>
  <divclass="item"> 
  xxxx
  </div>
  <div class="item"> 
  xxxx
  </div>
</div>
.item{
 width: calc((100% - 14px) / 3);
    // height: 30%; 
    padding-top: 14%;
    padding-bottom: 14%;
    min-width: calc((100% - 14px) / 3);
    max-width: calc((100% - 14px) / 3);
    &:nth-child(3n) { 
      margin-right: 0;
    }
}

这个方法使用padding 以元素width 为基准来自适应高度。 而且是 分开 top + bottom ,这样还间接实现item里的元素垂直居中的效果

\color{#228B22}{前端学习小总结,不对之处,欢迎大神们喷我。可以的话顺手点个赞吧~~!}
\color{red}{警: 禁止抄袭,转载说明出处 }

上一篇 下一篇

猜你喜欢

热点阅读