使用margin:auto
-
父容器使用相对定位,并设置
宽
和高
-
子元素使用绝对定位,并且
left
,right
,top
,bottom
都设置为0,margin
设置为auto
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
margin: 0;
padding: 0;
}
.content {
background: #ee2c37;
width: 400px;
height: 400px;
position: relative;
}
.item {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 200px;
height: 200px;
background: #69ee20;
margin: auto;
}
</style>
</head>
<body>
<div class="content">
<div class="item"></div>
</div>
</body>
</html>
marign负值法
-
父容器使用相对定位,并设置
宽
和高
-
子元素使用绝对定位,并设置
top
和left
的值为50%
-
使用margin的负值将元素移到中间,
margin-top
为元素height/2
的负值,margin-left
为元素width/2
的负值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
margin: 0;
padding: 0;
}
.content {
background: #ee2c37;
width: 400px;
height: 400px;
position: relative;
}
.item {
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
margin-left: -100px;
margin-top: -100px;
background: #69ee20;
}
</style>
</head>
<body>
<div class="content">
<div class="item"></div>
</div>
</body>
</html>
使用table-cell
-
父元素的
display
属性设置为table-cell
,设置宽和高 -
在垂直方向上居中对齐,在水平方向上居中对齐
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
margin: 0;
padding: 0;
}
.content {
background: #ee2c37;
width: 400px;
height: 400px;
display: table-cell;
vertical-align: middle;
text-align: -webkit-center;
text-align: -moz-center;
}
.item {
width: 200px;
height: 200px;
background: #69ee20;
}
</style>
</head>
<body>
<div class="content">
<div class="item"></div>
</div>
</body>
</html>
这个有兼容性的问题,如果直接设置
text-align: center;
,在浏览器上是不会居中的,谷歌浏览器需要设置为text-align: -webkit-center;
,火狐浏览器需要设置为text-align: -moz-center;
flex布局
-
将父容器设置为一个
flex
容器 -
在垂直的交叉轴上居中对齐,在水平的主轴上居中对齐
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
margin: 0;
padding: 0;
}
.content {
background: #ee2c37;
width: 400px;
height: 400px;
display: flex;
justify-content: center;
align-items: center;
}
.item {
width: 200px;
height: 200px;
background: #69ee20;
}
</style>
</head>
<body>
<div class="content">
<div class="item"></div>
</div>
</body>
</html>