1、行内元素
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#test{
width: 200px;
height: 200px;
line-height: 200px;
background: pink;
margin: 0 auto;
text-align: center;
}
</style>
</head>
<body>
<div id="test">
test
</div>
</body>
</html>
2、块级元素
已知宽高
方式一:绝对定位+margin反向偏移
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<!--已知高度的元素水平垂直居中方案-->
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#wrap{
position: relative;
width: 400px;
height: 600px;
background: pink;
margin: 0 auto;
}
#inner{
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
width: 100px;
height: 100px;
background: deeppink;
}
</style>
</head>
<body>
<div id="wrap">
<div id="inner">
test
</div>
</div>
</body>
</html>
方式二:绝对定位+margin:auto
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<!--已知高度的元素水平垂直居中方案-->
<!--
绝对定位盒子的特性
高宽有内容撑开
水平方向上: left + right + width + padding + margin = 包含块padding区域的尺寸
0 0 100 0 0 400
垂直方向上: top + bottom + height + padding + margin = 包含块padding区域的尺寸
0 0 100 0 0 600
-->
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#wrap{
position: relative;
width: 400px;
height: 600px;
background: pink;
margin: 0 auto;
}
#inner{
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
width: 100px;
height: 100px;
background: deeppink;
}
</style>
</head>
<body>
<div id="wrap">
<div id="inner">
test<br />
test<br />
test<br />
test<br />
</div>
</div>
</body>
</html>
未知宽高
方式一:绝对定位+transform反向偏移
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<!--未知高度的元素水平垂直居中方案-->
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#wrap{
position: relative;
width: 400px;
height: 600px;
background: pink;
margin: 0 auto;
}
#inner{
position: absolute;
left: 50%;
top: 50%;
transform: translate3d(-50%,-50%,0);
background: deeppink;
}
</style>
</head>
<body>
<div id="wrap">
<div id="inner">
testtesttesttesttesttesttest<br />
testtesttesttesttesttesttest<br />
testtesttesttesttesttesttest<br />
testtesttesttesttesttesttest<br />
testtesttesttesttesttesttest<br />
testtesttesttesttesttesttest<br />
</div>
</div>
</body>
</html>
参考:
https://segmentfault.com/a/1190000006108996
https://segmentfault.com/a/1190000014116655