绝对定位与浮动类似,也是会脱离文档流;绝对定位的方式实现居中,需要在已知宽高的情况下;
代码如下:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>居中</title>
<style type="text/css">
.container {
width: 600px;
height: 300px;
background-color: #ccc;
position: relative;
}
.center-p {
background-color: yellow;
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 80px;
margin: auto; /*先水平居中*/
margin-top: -50px;
margin-left: -40px;
}
</style>
</head>
<body>
<div class="container">
<div class="center-p">
table-cell居中
</div>
</div>
</body>
</html>
Paste_Image.png
网友评论