html--垂直居中
<!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>
和上边图片一样,思路不一样
古人学问无遗力,少壮工夫老始成。
纸上得来终觉浅,绝知此事要躬行。

浙公网安备 33010602011771号