元素各种水平垂直居中方式
程序员文章站
2022-04-25 14:31:20
...
1.在浮动元素外面再嵌套一层div
<div id="container">
<div class="content">
<div class="left">我是一个居中元素</div>
</div>
</div>
#container{
width:200px;
height:200px;
border:1px solid black;
text-align: center;
}
#container div.left{
width:100px;
height:100px;
float:left;
background-color: #b00000;
}
.content{
margin:auto;
width: 100px;
height:100px;
}
显示效果:
2.使用绝对定位来进行居中(没有浮动):
#container{
width:200px;
height:200px;
border:1px solid black;
position: relative;
text-align: center;
}
#container div.left{
width:100px;
height:100px;
background-color: #b00000;
position: absolute;
left:50%;
top:50%;
margin-left: -50px;
margin-top: -50px;
}
<div id="container">
<div class="left"></div>
</div>
显示效果:
3.另一种使用绝对定位的方式(没有浮动):
#container{
width:200px;
height:200px;
border:1px solid black;
position: relative;
text-align: center;
}
#container div.left{
width:100px;
height:100px;
background-color: #b00000;
left:0px;
right:0px;
top:0px;
bottom:0px;
position: absolute;
margin:auto;
}
<div id="container">
<div class="left"></div>
</div>
显示效果:
4.使用绝对定位和translate()位移函数:
.parent{
position:relative;
background-color: #b00000;
width: 200px;
height: 200px;
}
.child {
background-color: #2da77a;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%)
}
<div class="parent">
<div class="child">测试文字</div>
</div>
显示效果:
5.使用相对定位使浮动元素水平居中:
注意:.box不能设置width,因为要保证 .box和p的宽度是一致的,left:50%是相对于父元素的宽度
.container{
width: 400px;
height: 200px;
border:1px solid black;
}
.box{
float:left;
position:relative;
left:50%;
background-color: #b00000;
}
p{
float:left;
background-color: #2da77a;
position:relative;
right:50%;
}
<div class="container">
<div class="box">
<p>我是浮动的</p>
<p>我也是居中的</p>
</div>
</div>
显示效果: