<!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;
margin: 0 auto;
text-align:center;
background: pink;
}
</style>
</head>
<body>
<div id="test">
test
</div>
</body>
</html>
2 已經知道塊元素的高寬垂直方案
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
*{ margin: 0; padding: 0;}
/*已知寬高的水平垂直居中方案*/
#wrap{
position: relative;
width: 150px;
height: 150px;
background: pink;
margin: 0 auto;
}
#inner{
position: absolute;
left: 50%;
top:50%;
margin-left: -50px;
margin-top:-50px;
width: 100px;
height: 100px;
background: deeppink;
text-align: center;
line-height: 100px;
}
</style>
</head>
<body>
<div id="wrap">
<div id="inner">
test
</div>
</div>
</body>
</html>

3
<!--已知高度的元素水平垂直居中方案-->
<!--
絕對定位盒子的特性
高寬有內容撐開
水平方向上: left + right + width + padding + margin = 包含塊padding區域的尺寸
0 0 100 0 0 400
垂直方向上: top + bottom + height + padding + margin = 包含塊padding區域的尺寸
0 0 100 0 0 600
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
*{ margin: 0; padding: 0;}
/*已知寬高的水平垂直居中方案*/
#wrap{
position: relative;
width: 150px;
height: 150px;
background: pink;
margin: 0 auto;
}
#inner{
position: absolute;
left: 0;
top:0;
right: 0;
bottom: 0;
/*知識點*/
margin: auto;
width: 100px;
height: 100px;
background: deeppink;
text-align: center;
}
</style>
</head>
<body>
<div id="wrap">
<div id="inner">
test<br />
test<br />
test<br />
test<br />
</div>
</div>
</body>
</html>
和上邊圖片一樣,思路不一樣
4<!--未知高度的元素水平垂直居中方案--> 注意!!!兼容性不好,部分瀏覽器不兼容
<!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>
和上邊圖片一樣,思路不一樣
