css常用的垂直居中

css常用的垂直居中

这里是引用

1.父相子绝–给定子盒子的尺寸(margin

父盒子相对定位,子盒子绝对定位
使用前提

必须提前知道被居中块级元素的尺寸,否则无法准确实现垂直居中。

效果如图

在这里插入图片描述
css代码

#box {
    width: 300px;
    height: 300px;
    background: #ddd;
    position: relative;
}
#child {
    width: 150px;
    height: 100px;
    background: orange;
    position: absolute;
    top: 50%;
    margin: -50px 0 0 0; 
}

html代码

<div id="box">
    <div id="child"></div>
</div>

2.父相子绝–可以不给定子盒子的尺寸(transform

transform 中 translate 偏移的百分比就是相对于元素自身的尺寸而言的。

<div id="box">
    <div id="child">test vertical align</div>
</div>

css代码

#box {
    width: 300px;
    height: 300px;
    background: #ddd;
    position: relative;
}
#child {
    background: orange;
    position: absolute;
    top: 50%;
    transform: translate(0, -50%);
}

3.父相子绝–(margin: auto

前提

知道元素的宽高,图片这种自身就包含尺寸的元素不用设置

top和bottom设为相等的值,只要两者相等就行

css代码

#box {
    width: 300px;
    height: 300px;
    background: #ddd;
    position: relative;
}
#child {
    width: 200px;
    height: 100px;
    background: orange;
    position: absolute;
    top: 0;
    bottom: 0;
    margin: auto;
    line-height: 100px;
}

html代码

<div id="box">
    <div id="child">test vertical align</div>
</div>

4. 父元素使用(padding

前提

父元素是不能设置高度的,要让它自动被填充起来,除非设置了一个正好等于上内边距+子元素高度+下内边距的值,否则无法精确垂直居中。

css代码

#box {
    width: 300px;
    background: #ddd;
    padding: 100px 0;
}
#child {
    width: 200px;
    height: 100px;
    background: orange;
}

html

<div id="box">
    <div id="child"></div>
</div>

5. 父盒子使用flex布局

flex布局参考文章
http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html
适用于行内元素与块级元素
css

#box {
    width: 300px;
    height: 300px;
    background: #ddd;
    display: flex;
    align-items: center;
}
#child {
    width: 300px;
    height: 100px;
    background: orange;
}

html

<div id="box">
    <div id="child"></div>
</div>

6.单行文本居中

line-height等于height

#box{
    width: 300px;
    height: 300px;
    background: #ddd;
    line-height: 300px;
}

7. 图片居中

使用 line-height 和 vertical-align 对图片进行垂直居中

css

#box{
    width: 300px;
    height: 300px;
    background: #ddd;
    line-height: 300px;
}
#box img {
    width: 200px;
    height: 200px;
    vertical-align: middle;
}

html

<div id="box">
    <img src="smallpotato.jpg">
</div>

8. 对容器里的文字进行垂直居中

使用 display: table; 和 vertical-align: middle;

css

#box {
    width: 300px;
    height: 300px;
    background: #ddd;
    display: table;
}
#child {
    display: table-cell;
    vertical-align: middle;
}

html

<div id="box">
    <div id="child">test vertical align</div>
</div>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

RDSunday

爱,就供养;喜欢/受益,就打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值