设为首页 - 加入收藏 ASP站长网(Aspzz.Cn)- 科技、建站、经验、云计算、5G、大数据,站长网!
热搜: 创业者 数据 手机
当前位置: 首页 > 综合聚焦 > 编程要点 > 正文

css元素垂直居中展示有哪些完成方法?

发布时间:2022-01-12 12:50 所属栏目:13 来源:互联网
导读:css元素垂直居中展示有哪些实现方法?在实际的项目中,实现元素垂直居中的需求还是比较常见的,而实现元素垂直居中的方法有很多,本文给大家分享几个方法,需要的朋友可以参考。 【一】知道居中元素的宽高 absolute + 负margin 代码实现 .wrapBox5{ width: 3
  css元素垂直居中展示有哪些实现方法?在实际的项目中,实现元素垂直居中的需求还是比较常见的,而实现元素垂直居中的方法有很多,本文给大家分享几个方法,需要的朋友可以参考。
 
  【一】知道居中元素的宽高
 
  absolute + 负margin
 
  代码实现
 
  .wrapBox5{
      width: 300px;
      height: 300px;
      border:1px solid red;
      position: relative;
  }
  .wrapItem5{
      width: 100px;
      height: 50px;
      position: absolute;
      background:yellow;
      top: 50%;
      left:50%;
      margin-top: -25px;
      margin-left: -50px;
  }
  运行结果
 
 
 
  absolute + margin auto
 
  代码实现
 
  .wrapBox{
      width: 300px;
      height: 300px;
      background: yellow;
      position: relative;
  }
  .wrapItem{
      width: 100px;
      height: 50px;
      background:green;
      display: inline-block;
      position: absolute;
      top: 0px;
      bottom:0px;
      left: 0px;
      right: 0px;
      margin:auto;
  }
 
 
  absolute + calc
 
  代码实现
 
  .wrapBox6{
      width: 300px;
      height: 300px;
      border:1px solid green;
      position: relative;
  }
  .wrapItem6{
      width: 100px;
      height: 50px;
      position: absolute;
      background:yellow;
      top: calc(50% - 25px);
      left:calc(50% - 50px);
  }
  运行结果
 
 
 
  三种对比总结
 
  当居中元素知道宽高的时候,设置居中的方式比较简单单一。三种方法的本质是一样的,都是对居中元素进行绝对定位,在定位到上50%,左50%后再拉回居中元素的一半宽高实现真正的居中。三种方式的区别就在于拉回元素本身宽高的方式不同。
 
  【二】居中元素的宽高未知
 
  absolute + transform
 
  代码实现
 
  .wrapBox{
      width: 300px;
      height: 300px;
      background:#ddd;
      position: relative;
  }
  .wrapItem{
      width: 100px;
      height: 50px;
      background:green;
      position: absolute;
      top: 50%;
      left:50%;
      transform: translate(-50% , -50%);
  }
  运行结果
 
 
 
  原理
  原理类似于已知宽高的实现方式,只不过当前居中元素宽高未知,所以需要自动获取当前居中元素的宽高。translate属性正好实现了该功能。
 
  优缺点
  优点:自动计算本身的宽高
  缺点:如果同时使用transform的其他属性会产生相互影响。
  所以:在不使用transform的其他属性时推荐使用该方式
 
  flex布局
 
  .wrapBox2{
      width: 300px;
      height: 300px;
      background: blue;
      display: flex;
      justify-content: center;
      align-items: center;
  }
  /*注意:即使不设置子元素为行块元素也不会独占一层*/
  .wrapItem2{
      width: 100px;
      height: 50px;
      background:green;
  }

(编辑:ASP站长网)

    网友评论
    推荐文章
      热点阅读