文档
div绝对定位水平垂直居中(未知容器,已知元素宽高)
方案一:margin:auto实现绝对定位元素的居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<style>
body{
background: #f00;
}
.div1 {
width: 200px;
height: 200px;
background: green;
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
</style>
<title>Document</title>
</head>
<body>
<div class="div1"></div>
</body>
</html>
效果
方案二:margin 负间距
这或许是当前最流行的使用方法。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<style>
body {
background: #f00;
}
.div1 {
width: 200px;
height: 200px;
background: green;
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
}
</style>
<title>Document</title>
</head>
<body>
<div class="div1"></div>
</body>
</html>
效果与上面一样
方案三:Transforms 进行平移
兼容性:IE8不支持;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<style>
body {
background: #f00;
}
.div1 {
width: 200px;
height: 200px;
background: green;
position: absolute;
left: 50%; /* 定位父级的50% */
top: 50%;
transform: translate(-50%, -50%); /*自己的50% */
}
</style>
<title>Document</title>
</head>
<body>
<div class="div1"></div>
</body>
</html>
方案四:使用flex,已知容器,已知元素宽高
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<style>
.box {
height: 600px;
display: flex;
justify-content: center;
align-items: center;
background: #f00;
/* aa只要三句话就可以实现不定宽高水平垂直居中。 */
}
.box > div {
background: green;
width: 200px;
height: 200px;
}
</style>
<title>Document</title>
</head>
<body>
<div class="box">
<div class="div1"></div>
</div>
</body>
</html>
table-cell布局
因为table-cell相当与表格的td,td为行内元素,无法设置宽和高,所以嵌套一层,嵌套一层必须设置display: inline-block;td的背景覆盖了橘黄色,不推荐使用
<div class="box">
<div class="content">
<div class="inner">
</div>
</div>
</div>
.box {
background-color: #FF8C00;//橘黄色
width: 300px;
height: 300px;
display: table;
}
.content {
background-color: #F00;//红色
display: table-cell;
vertical-align: middle;//使子元素垂直居中
text-align: center;//使子元素水平居中
}
.inner {
background-color: #000;//黑色
display: inline-block;
width: 20%;
height: 20%;
}