方案一:绝对定位——上下左右为0,margin为auto
- 父元素position设为relative,子元素position设为absolute,子元素margin设为auto,left,top,right,bottom设为0
<style type="text/css">
.wrap{
width: 200px;
height: 200px;
border: 1px #000 solid;
position: relative;
}
.box{
width: 50px;
height: 50px;
border: 1px solid red;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
<div class="wrap">
<div class="box">哈哈</div>
</div>
方案二:绝对定位——margin为负一半
- 父元素position设为relative,子元素position设为absolute,子元素left,top设为50%,margin-left,margin-top设为负子元素的一半
.box{
width: 50px;
height: 50px;
border: 1px solid red;
position: absolute;
left: 50%;
top: 50%;
margin-left: -25px;
margin-top: -25px;
}
方案三:绝对定位——transform变形
- 父元素position设为relative,子元素position设为absolute,子元素left,top设为50%,transform的translate设为-50%
.box{
width: 50px;
height: 50px;
border: 1px solid red;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
方案四:弹性盒模型
- 父元素的display设为flex,justify-content和align-items设为center
.wrap{
width: 200px;
height: 200px;
border: 1px #000 solid;
display: flex;
justify-content: center;
align-items:center;
}
方案五:table-cell
- 父元素display设为table-cell,vertical-align设为middle,text-align设为center,子元素display设为inline-block,vertical-align设为middle
.wrap{
width: 200px;
height: 200px;
border: 1px #000 solid;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.box{
width: 50px;
height: 50px;
border: 1px solid red;
display: inline-block;
vertical-align: middle;
}
方案六:仅适用于单行文本
- 父元素text-align设为center,line-height设为父元素的高度。
.wrap{
width: 200px;
height: 200px;
border: 1px #000 solid;
text-align: center;
line-height: 200px;
}
<div class="wrap">
<div class="box">哈哈</div>
</div>
网友评论