CSS水平居中

一、使用text-align:

1.子元素为行内元素:在其父元素上设置text-align:center;

<div class="father1 fCommon">
    <div class="children1 cCommon">
        text-align:center;
        display:inline-block;
    </div>
</div>
.father1{
    text-align: center;
}
.children1{
    
}

在这里插入图片描述
2.子元素为块级元素,子元素上添加 display:inline-block;使其变为行内块元素。
缺点:子元素的文字会水平居中。

.father1{
    text-align: center;
}
.children1{
    display:inline-block;
}

在这里插入图片描述

二、使用 margin:0 auto;

1、子元素为块元素。

<div class="father2 fCommon">
    <div class="children2 cCommon">
        margin:0 auto;
    </div>
</div>
.children2{
   margin:0 auto;
}

在这里插入图片描述

2、若子元素设置有宽度则可以使用绝对定位的盒模型属性,实现居中效果;若不设置宽度时,子元素被拉伸。

		.father2{
            margin:0 auto;
            position: relative;
        }
        .children2{
            margin:0 auto;
            position: absolute;
            width: 100px;
            left: 0;
            right: 0;
        }

在这里插入图片描述

三、absolute绝对定位:

通过绝对定位的偏移属性实现绝对居中。

1、配合translate()位移函数。 translate函数的百分比是相对于自身宽度的,所以left:50%配合translateX(-50%)可实现居中效果。

<div class="father3 fCommon">
    <div class="children3 cCommon">
        position:absolute
        通过绝对定位的偏移属性实现水平居中
        配合translate()位移函数
        translate()位移函数的百分比是相对于自
        身宽度
        left:50%配合translateX(-50%)
    </div>
</div>
		.father3{
            margin:20px auto;
            position: relative;
        }
        .children3{
            position: absolute;
            left: 50%;
            transform: translateX(-50%);
        }

在这里插入图片描述

四、flex布局
1、在伸缩容器上设置主轴对齐方式justify-content:center
<div class="father6 fCommon" style="display: flex;justify-content: center">
    <div class="children6 cCommon">
        flex布局
    </div>
</div>

在这里插入图片描述
2、不建议采用:(会脱离布局的意义) 在伸缩项目上设置margin: 0 auto

<div class="father6 fCommon" style="display: flex;">
    <div class="children6 cCommon" style="margin: 0 auto;">
        flex布局
    </div>
</div>

在这里插入图片描述

grid布局:

1、在容器上设置:

<div  class="father7 fCommon" style="display: grid;justify-items: center">
    <div class="children7 cCommon" style="margin: 0 auto;">
        grid布局
    </div>
</div>

在这里插入图片描述
2、不建议采用:(会脱离布局的意义) 在子项目上设置margin:0 auto;

<div  class="father7 fCommon" style="display: grid;">
    <div class="children7 cCommon" style="margin: 0 auto;">
        grid布局
    </div>
</div>

在这里插入图片描述

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值