一、常用的一些居中的方法
- 绝对定位
(1)知道元素的尺寸
.box {
width: 300px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -150px;
}
(2)元素尺寸未知
.box {
background: pink;
width: 300px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);/*50%为自身尺寸的一半*/
}
该方法兼容性较差,不支持IE8

- 用margin: auto;实现定位
.box {
background: pink;
width: 300px;
height: 200px;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
top left bottom right 都要为0,IE8+都能兼容。详情参考张鑫旭的文章:小tip: margin:auto实现绝对定位元素的水平垂直居中
-
单行文本居中
image.png
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>单行文本居中</title>
<style>
p {
border: 1px solid;
font-size: 16px;
height:3em;
line-height: 3em;
text-align: center;
}
</style>
</head>
<body>
<div class="box"></div>
<p>单行文本居中</p>
</body>
</html>
网友评论