CSS设置行内元素和块级元素的水平垂直居中

本文介绍了CSS中块级和行内元素的水平垂直居中方法,包括使用text-align、line-height、绝对定位、Flex布局和Transform等多种技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么是块级元素:会自动占据一定矩形空间,可以通过设置高度、宽度、内外边距等属性,来调整的这个矩形的样子。
常见的块级元素:div、ul、li、dl、dt、dd、p、h1-h6、blockquote

什么是行内元素:没有自己独立的空间,它是依附于其他块级元素存在的,因此,对行内元素设置高度、宽度、内外边距等属性,都是无效的
常见的行内元素:a、b、span、img、input、strong、select、label、em、button、textarea

行内元素水平垂直居中方法

1.水平居中:给父级设置

div{
	text-align : center;
}

2垂直居中:

div {
    height: 100px;
    line-height: 100px;
}

3.既要水平居中又要垂直居中:

div {
    height: 100px;
    text-align: center;
    line-height: 100px;
}

块级元素水平垂直居中方法

html

<div class="box1">
        <div class="box2">水平垂直居中</div>
    </div>

在这里插入图片描述

需要知道子元素的宽高

1.Margin为负值
父级节点相对定位,居中块绝对定位
top:50%; left:50%;
margin-top: -height/2; margin-left: -width/2

.box1 {
    width: 200px;
    height: 200px;
    background-color: #eee;
    position: relative;
}

.box2 {
    position: absolute;
    width: 100px;
    height: 100px;
    background-color: red;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px
}

2.绝对定位
父级节点相对定位,居中块绝对定位,top:0;left:0;right:0;bottom:0;margin:auto;

.box1 {
    width: 200px;
    height: 200px;
    background-color: #eee;
    position: relative;

}
.box2 {
    position: absolute;
    width: 100px;
    height: 100px;
    background-color: red;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}

3.absolute + calc()函数
父级节点相对定位,居中块绝对定位
left: calc(50% - width/2);
top: calc(50% -height/2;

.box1 {
    width: 200px;
    height: 200px;
    background-color: #eee;
    position: relative;

}
.box2 {
    position: absolute;
    width: 100px;
    height: 100px;
    background-color: red;
    left: calc(50% - 50px);
    top: calc(50% - 50px);
}

不需要知道子元素的宽高

1.Flex布局
父元素设置,主轴和交叉轴均为center

.box1 {
    display: flex;
    justify-content: center; //水平居中
    align-items: center; //垂直居中
}

2.利用css3的属性Transform
父级节点相对定位,居中块绝对定位
子元素:top:50%; left:50%; transform: translate(-50%, -50%)

.box1 {
    width: 200px;
    height: 200px;
    background-color: #eee;
    position: relative;
}

.box2 {
    position: absolute;
    background-color: red;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值