CSS实现垂直居中

1、line-height实现垂直居中

代码:

html

div class="content">单行文本居中</div>

css

.content {
    height: 200px;
    background-color: aquamarine;
    line-height: 200px;
    text-align: center;
}

适用于单行文本


2、line-height + vertical-align实现垂直居中

代码:

html

<div class="parent">
    <div class="son">
	多行文本居中,多行文本居中,多行文本居中,多行文本居中,多行文本居中,多行文本居中,多行文本居中
    </div>
</div>

css

.parent {
    height: 200px;
    width: 400px;
    background-color: #4f7568;
    line-height: 200px;
    margin: 0 auto;
}
.son {
    line-height: 20px;
    display: inline-block;
    vertical-align: middle;
}

适用于多行文本


3、margin和absolute实现垂直居中(1)

代码:

html

<div class="parent">
	<div class="son">
	</div>
</div>
css
height: 200px;
    background-color: #4f7568;
    position: relative;
}
.son {
    width: 400px;
    height: 100px;
    background: aquamarine;
    margin-top: -50px;
    position: absolute;
    top: 50%;
    margin-left: 200px;
}


4、margin和absolute实现垂直居中(2)

代码:

html

<div class="parent">
    <div class="son">
    </div>
</div>

css

.son {
    width: 400px;
    height: 100px;
    background: aquamarine;
    margin: auto;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

利用绝对定位元素的流体特性和margin:auto的自动填充规则现实居中效果,不用管parent元素的高度

适用于块级元素


5、使用flex布局实现垂直居中

代码:

html

<div class="parent">
    <div class="son">
    </div>
</div>

css

.parent {
    height: 200px;
    background-color: #4f7568;
    display: flex;
    justify-content: center;
    align-items: center;
}
.son {
    width: 400px;
    height: 100px;
    background: aquamarine;
}

适用于块级元素



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值