行内 inline 元素: text-align: center;
块级 block 元素: margin: 0 auto;
absolute 定位元素 left: 50%;margin-left 负值
<style>
.box{
height: 100px;
border: 1px solid #ccc;
margin: 30px 0;
}
.item{
background-color: #ccc;
}
.box-1{
text-align: center;
line-height: 100px;
}
.box-2 .item{
width: 200px;
height: 50px;
margin: 0 auto;
}
.box-3{
position: relative;
}
.box-3 .item{
position: absolute;
left: 50%;
margin-left: -100px; /*移动子元素宽度的一半*/
width: 200px;
height: 50px;
}
</style>
<div class="box box-1">
<span> 行内 inline 元素</span>
</div>
<div class="box box-2">
<div class="item">块级 block 元素</div>
</div>
<div class="box box-3">
<div class="item">absolute 定位元素</div>
</div>
网友评论