定位居中
使用定位后,盒子使用 margin:0 auto 居中就失效了(浮动也会导致 margin:0 auto 失效),所以要特殊处理。
笔记内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>定位居中</title>
<style>
/* 因为使用定位后,盒子使用 margin:0 auto 居中就失效了(浮动也会导致 margin:0 auto 失效),所以要特殊处理。 */
/* 让定位的盒子水平居中 */
.content{
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
left: 50%; /* 距离左边 50% */
margin-left: -100px; /* 往左移动盒子的一半 */
}
/* 让定位的盒子水平垂直居中 */
.zhong{
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
left: 50%; /* 距离左边 50% */
margin-left: -100px; /* 往左移动盒子的一半 */
top: 50%; /* 距离上边 50% */
margin-top: -100px; /* 往下移动盒子的一半 */
}
</style>
</head>
<body>
<div class="content">
content
</div>
<div class="zhong">
zhong
</div>
</body>
</html>