绝对居中
相对定位
效果:
html
<body>
<div></div>
</body>
css
<style type="text/css">
div{
width:200px;
height:200px;
background-color:pink;
position:relative;left:50%;margin-left:-100px;
}
</style>
- 注意:相对定位只可以设置其水平居中,若设置水平垂直居中,必须使用绝对定位
绝对定位
效果:
html
<body>
<div></div>
</body>
css
<style type="text/css">
div{
width:200px;
height:200px;
background-color:pink;
position:absolute;left:50%;top:50%;
margin-left:-100px;
margin-top:-100px;
}
</style>
- 绝对定位事实上是负margin的一种应用
flex
效果:
html
<body>
<div class="box">
<div></div>
</div>
</body>
css
<style type="text/css">
.box{
width:300px;
height:300px;
background-color:pink;
display:flex;
justify-content:center;
align-items:center;
margin:0 auto;
}
.box div{
width:100px;
height:100px;
background-color:blue;
}
</style>
- 注意:justify-content,align-items是容器的属性,不可以对项目使用