Css实现水平垂直居中的几种方法
下面介绍几种常见的水平垂直居中的方法,CSS实现水平垂直的方法是不唯一的,也是前端基础长问到的一个问题,需要我们去了解。
先创建一个基本的html代码和样式
代码具体如下:
<div class="wrap">
外层
<div class="center">内部</div>
</div>
.wrap{
width: 300px;
height: 300px;
background-color:darkgoldenrod;
position:relative;
}
.center{
width: 150px;
height: 150px;
background-color:rgb(31, 107, 231);
position: absolute;
}
1、定位+需要定位的元素的margin值减去宽高的一半
这个方法的前提是需要知道居中元素的宽高
.center{
position: absolute;
left: 50%;
top: 50%;
margin-left: -75px;
margin-top: -75px;
}
2、定位+margin:auto
具体实现如下:
就是将需要居中的子元素的margin:auto,定位后,将left,top,right,bottom的值都设置为0
该方法在不知道居中元素的宽高时也可以使用
.center{
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto
}
3、定位+CSS3中的transform
需要注意的是,该方法设计CSS3的知识,浏览器可能存在兼容问题
.center{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
4、flexBox居中
注意:该方法作用在父元素上,一般在制作移动端页面时,使用
.wrap{
display: flex;
justify-content: center;
align-items: center
}