您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

使用CSS实现垂直居中的7种方法分享

2025/3/13 17:08:09发布20次查看
今天申请博客通过了,给大家讲讲我所看到过的纯css实现垂直居中的各种方法。为什么要把它作为第一篇文章呢?因为这是我刚开始接触前端学到的对我最有用的知识,希望大家也可以从中获益!
在css中实现水平居中是非常简单的,行内元素设置其父元素的text-align:center,块级元素就对其自身应用magrin:auto。然而,实现垂直居中就有点麻烦了,首先它是极其常见的需求,看似简单,在实践中,往往难如登天,当设计尺寸不固定时尤其如此。以下是我找到的一些方法:
方法一:行高line-height
(1)单行文本居中
html代码
<p class="box1"> <p class="box2">垂直居中</p> </p>
css代码
 .box1{    height: 200px;  }  .box2{   line-height: 200px;  }
(2)图片垂直居中
html代码
 <p class="box1">    <img src="images/bg-sun.png" alt="">  </p>
css代码
 .box1{    line-height:200px;  }  .box1 img{    vertical-align: middle;  }
方法二:table-cell
css代码
 .box1{    display: table-cell;    vertical-align: middle;    text-align: center;  }
方法三:display:flex
(1)css代码
 .box1{    display: flex;  }  .box2{    margin:auto;  }
(2)css代码
 .box1{    display: flex;    justify-content:center;    align-items:center;  }
方法四:绝对定位和负边距
(1)css代码
 .box1{     position: relative;   }     .box2{     position: absolute;     top: 50%;     left: 50%;     margin-top: -10px;/*减去子元素高度一半*/     margin-left:-32px;/*减去子元素宽度一半*/  }
(2)css代码
 .box2{    position: absolute;    top:calc(50% - 10px);/*减去子元素高度一半*/    left:calc(50% - 32px);/*减去子元素宽度一半*/  }
方法五:绝对定位和0
css代码
 .box2{    width: 50%;    height: 50%;    background: #555;    overflow: auto;    margin: auto;    position: absolute;    top: 0; left: 0; bottom: 0; right: 0;      }
方法六:translate
(1)css代码
 .box2{    position: absolute;    top:50%;    left:50%;    transform:translate(-50%,-50%);  }
(2)html代码
 <body>  <p class="box1">  </p>  </body>
css代码
 .box1{    width: 200px;    height: 200px;    background: #666;    margin: 50vh auto 0;    transform: translatey(-50%);  }
方法七:display:-webkit-box
css代码
 .box2{    display: -webkit-box;    -webkit-box-pack:center;    -webkit-box-align:center;    -webkit-box-orient: vertical;    text-align: center7 }
以上就是使用css实现垂直居中的7种方法分享的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product