css实现元素居中的方法汇总

css实现居中的方法有非常多,所以这里不会全部列举。就选择自己比较喜欢的几种居中方式介绍一下。

推荐几篇关于“css居中”的文章供大家深入学习:

一、css垂直居中的11种方式

二、六种实现元素水平居中的方式

三、Centering in CSS:A Complete Guide(国外大牛)

 

简要介绍一下(详细应用可参考上面的三篇文章)。

 

水平居中:

方法一margin:0 auto;//固定宽度


方法二:display:inline-block配合text-align:center;(宽度不用固定)
举例:

body{//父元素
    text-align: center;
}
.div1{
    display: inline-block;
}

方法三display:flex;配合justify-content: center;(宽度不用固定)
举例:

body{
    display: flex;
    justify-content: center;

    height: 300px;
    background-color: red;
}
<div class="div1" style="height: 300px;background-color: red;">
    我是一段无足轻重的文字
</div>


方法四:width: fit-content; 配合margin:0 auto;(宽度不用固定)
举例:

.div1{
    width: fit-content; 
    margin:0 auto;
}
<div class="div1" style="height: 300px;background-color: red;">
    我是一段无足轻重的文字
</div>


方法五定位配合负margin值(固定宽度)
举例:

.div1{
    position: relative;/*绝对定位也一样*/
    left: 50%;
    margin-left: -200px;
}
<div class="div1" style="width:400px;height: 300px;background-color: red;">
    我是一段无足轻重的文字
</div>



方法六:浮动配合相对定位(要有一层父元素包裹)
举例:

.div1{
    position: relative;
    left: -50%;
}
.container{
    float: left;
    position: relative;
    left: 50%;
}
<div class="container">
    <div class="div1" style="height: 300px;background-color: red;">
        我是一段无足轻重的文字
    </div>
</div>

 

垂直居中:
方法一:绝对定位和负margin值(固定高度)
举例:

.div1{
    position: absolute;
    top:50%;
    margin-top: -150px;
}
<div class="div1" style="width:300px;height: 300px;background-color: red;">
    我是一段无足轻重的文字
</div>

方法二:绝对定位+tranlate(其实是方法1的变形:不过不用固定高度)
举例:

.div1{
    position: absolute;
    top:50%;
    transform: translate(0,-50%);
}
<div class="div1" style="width:20px;background-color: red;">
    我是一段无足轻重的文字
</div>

方法三绝对定位+0+margin:auto(固定宽度)
举例:

div1{
    position: absolute;
    top:0;
    bottom:0;
    margin:auto;
}
<div class="div1" style="width:300px;height: 300px;background-color: red;">
    我是一段无足轻重的文字
</div>


方法四:display:flex配合align-items:center;(写父元素上,注意body上面无效,不用固定高度)
举例:

.fa{
    display: flex;
    align-items: center;
}
<div class="fa" style="width:500px;height:500px;background-color: blue;">
    <div class="div1" style="width:200px;height:200px;background-color: red;">
        我是一段无足轻重的文字
    </div>
</div>

 

 

 

 

水平垂直居中就不做总结了,合适的综合水平居中和垂直居中即可。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值