0
点赞
收藏
分享

微信扫一扫

实现一个div垂直居中, 其距离屏幕左右两边各10px, 其高度始终是宽度的50%。同时div中有一个文字A,文字需要水平垂直居中。

南陵王梁枫 2022-03-15 阅读 58

html:

<div class="out">
    <div class="in">
      <div class="box">A</div>
    </div>
</div>

css:

        

html,
    body {
      /* 要让一个box的百分比高度height:100%起作用,
      需要给这个元素的所有父元素设定一个百分比高度height: 100%; */
      height: 100%;
    }

    .out {
      /* out为什么不跟in并成一个盒子是因为要设置margin值,
      width:100%再设置margin会导致溢出 */
      margin: 0 10px;
      height: 100%;
      /* 让块垂直居中 */
      display: flex;
      align-items: center;
    }

    .in {
      background-color: green;
      /* 子绝父相 */
      position: relative;
      width: 100%;
      height: 0;
      /* padding-bottom: 50% 计算是根据父元素的width的值计算的 */
      padding-bottom: 50%;
    }

    .box {
      width: 100%;
      height: 100%;
      font-size: 20px;
      background-color: red;
      /* justify-content 属性定义了项目在主轴上的对齐方式 这里是让A垂直居中 */
      display: flex;
      justify-content: center;
      align-items: center;
      position: absolute;
    }

疑惑:为什么in盒子高度为0,padding设置为宽度的50%之后,但是设置position:relative和box盒子设置绝对定位就有高度。没有设置定位就没有?

最后发现:醉了。。。父元素相对定位,绝对定位下的子元素宽高若设置为百分比,相对于父元素的(content+padding)值,不含border值

如果子元素不是绝对定位,宽高设置为百分比就是相对于父元素的宽高。标准盒模型下是content,ie盒模型是content+padding+border。

最后结果:

 

举报

相关推荐

0 条评论