css水平居中,垂直居中,水平垂直居中

本文详细介绍了使用CSS实现元素水平、垂直及同时水平垂直居中的多种方法,包括使用margin、transform、absolute定位、table布局、flex布局等,适用于不同场景下的布局需求。

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

1.水平居中

(1)如果父元素是块级元素,子元素是行内元素,要求子元素水平居中,可以在父元素上定义text-align:center来实现水平居中

(2)如果父元素和子元素都是块级元素,那么可以在子元素上设置margin:0 auto实现水平居中

(3)通过将父元素设置成table-cell,然后设置text-align:center。(慎用)

2.垂直居中

(1)如果子元素是行内块元素,则可以使用vertical-align:middle来实现垂直居中,但是经常会不起效果,谨慎使用,基于baseline对齐,关于vertical-align和baseline可以看看这篇博客https://www.cnblogs.com/starof/p/4512284.html?utm_source=tuicool&utm_medium=referral

(2)如果子元素是单行文本的话,可以设置子元素line-height的高度和父元素高度一致达到垂直居中。

  当然也可以用下面水平垂直居中的方法。

3.水平垂直居中

(1)绝对定位(position:absolute)+margin-top,margin-left负自身宽度一半的值

.parent{
    width: 600px;
    height: 600px;
    background-color:#380fff;
    position: relative;
}
.son{
    width: 200px;
    height: 200px;
    background-color: aqua;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -100px;
    margin-left: -100px;
}

(2)绝对定位(position:absolute)+transform:translate(-50%,-50%)

.parent{
    width: 600px;
    height: 600px;
    background-color:#380fff;
    position: relative;
}
.son{
    width: 200px;
    height: 200px;
    background-color: aqua;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);/*将元素向上和向左移动自身宽度的50%*/
}

(3)绝对定位(position:absolute)+ 各个方位距离0+margin:auto

.parent{
    width: 600px;
    height: 600px;
    background-color:#380fff;
    position: relative;
}
.son{
    width: 200px;
    height: 200px;
    background-color: aqua;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}

(4)绝对定位(position:absolute)+ calc(计算属性)

.parent{
    width: 600px;
    height: 600px;
    background-color:#380fff;
    position: relative;
}
.son{
    width: 200px;
    height: 200px;
    background-color: aqua;
    position: absolute;;
    top: calc(50% - 100px); 
    left: calc(50% - 100px); /*减去宽度和高度的一半*/
}

(5)table布局,但是现在都不推荐使用table布局了

(6)flex布局

.parent{
    width: 600px;
    height: 600px;
    background-color:#380fff;
    display: flex;
    justify-content: center;
    align-items: center;
}
.son{
    width: 200px;
    height: 200px;
    background-color: aqua;
}

水平垂直居中更详细的见https://segmentfault.com/a/1190000016389031?utm_source=tag-newest此博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值