元素各种水平垂直居中方式

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>

显示效果:




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值