美文网首页
css 实现正方形自适应 并且内容居中

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

作者: 南土酱 | 来源:发表于2023-06-14 15:41 被阅读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}{警: 禁止抄袭,转载说明出处 }

相关文章

  • 网页左右自动自适应居中

    网页左右自动自适应居中 html部分 我在中间,而且是随着内容宽度自动左右居中,无须你操心。 css部分 #tes...

  • vw 单位 android 4.4 下的一个小bug

    CSS3 vw 单位 100vw = 100% 视窗宽度100vh = 100% 视窗高度 这样实现自适应正方形(...

  • css常见问题自用

    内容居中 flex实现上下居中,最简单。 背景图片自适应,宽度100%还是高度100%。 1920/1080是背景...

  • 前端测试题

    HTML+CSS 1.div垂直水平居中?2.css盒子模型包含哪些?3.如何实现左边固定宽度右边自适应?4.什么...

  • CSS每日一题

    如何实现左边两栏一定比例,左栏高度随右栏高度自适应? css实现水平居中的几种方式https://blog.csd...

  • css实现自适应正方形

    1、vm单位 2、padding-top实现 3、padding-bottom实现 4、伪元素的margin-to...

  • CSS实现自适应正方形

    父级宽高不定,子级元素要宽高都是父级元素宽度的一半,即一个正方形 1. 利用padding来实现 2. 利用伪类来...

  • CSS实现自适应正方形

    情况1:实现固定宽高的正方形 情况2:实现自适应的正方形 方式一:vw vh1vw === 1%的宽度 方式二:将...

  • css实现自适应正方形

    方法一:使用 CSS3 的 vw,vh 单位 用 vw 或 % 单位设置宽度,用 vw 单位设置相同高度即可; 用...

  • css实现居中、自适应

    单列布局水平居中 水平居中的页面布局中最为常见的一种布局形式,多出现于标题,以及内容区域的组织形式,下面介绍四种实...

网友评论

      本文标题:css 实现正方形自适应 并且内容居中

      本文链接:https://www.haomeiwen.com/subject/ctfkydtx.html