实现目标:实现元素居中
实现方法:CSS定位
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../css/index.css" type="text/css">
</head>
<body>
<div class="wrapper">
<div class="box"></div>
</div>
</body>
</html>
.wrapper{
position: relative;
width: 200px;
height: 200px;
background-color: orange;
margin-left: 100px;
}
.box{
width: 50px;
height: 50px;
background-color: green;
}
如上图所示,现在我们想要让绿色方块的位置在橙色方块居中显示。
.box{
width: 50px;
height: 50px;
background-color: green;
position: absolute;
left: 50%;
top: 50%;
}
我们可以给绿色方块加上定位属性absolute,让他的left跟top设置为50%。但是我们发左顶点式剧中了,这并不是我们想要的效果。
.box{
width: 50px;
height: 50px;
background-color: green;
position: absolute;
left: 50%;
top: 50%;
/*给方块加上margin,margin的值为方块宽/高的一半*/
margin-top: -25px;
margin-left: -25px;
}
总结:
1 设置定位属性
2 left/top 设置为50%
3 margin-top 为 负的 元素高度的一半
4 margin-left 为 负的 元素宽度的一半