在不确定自身高度的情况下,用 CSS 实现元素垂直居中的3种方法

镜像文章:在不确定自身宽度的情况下,用 CSS 实现元素水平居中的2种方法

1.不知道自己高度的情况下, 利用绝对定位只需要以下三行(推荐)
在这里插入图片描述

<div class="parentElement">
    <div class="childElement">子元素垂直居中</div>
</div>
  
<style>
.parentElement{
    position: relative;
    height: 200px;
    background: blanchedalmond;
}
.childElement{
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}
</style>

2.若父容器下只有一个元素,且父元素设置了高度,则只需要使用相对定位即可

<div class="parentElement">
    <div class="childElement">子元素垂直居中</div>
</div>
  
<style>
.parentElement{
	height:200px;
    background: blanchedalmond;
}
.childElement {
	position: relative;
	top: 50%;
	transform: translateY(-50%);
}
</style>

3.不考虑兼容老式浏览器的话,用Flex布局简单直观一劳永逸

<div class="parentElement">
    <div class="childElement">子元素垂直居中</div>
</div>
  
<style>
.parentElement{
    display:flex;/*Flex布局*/
    display: -webkit-flex; /* Safari */
    align-items:center;/*指定垂直居中*/
    height: 200px;
    background: blanchedalmond;
}
</style>

4.表格居中,除了IE6/7都支持
在这里插入图片描述

<div class="parentElement">
    <div class="childElement">子元素垂直居中</div>
</div>
  
<style>
.parentElement { 
	display: table;
 	height: 200px; 
	background: blanchedalmond; 
 }
 
.childElement { 
	text-align: center; 
	display: table-cell; 
	vertical-align: middle; 
}
</style>

5.inline-block
在这里插入图片描述

<div class="parentElement">
	<div class="content">我是内容<br />我也是内容</div>
	<div class="actor">我不显示</div>
</div>
  
<style>
.parentElement { 
	height: 200px; 
	background: blanchedalmond;
}
.content { 
    display: inline-block; 
	vertical-align: middle;
}
.actor {
    display: inline-block; 
	vertical-align: middle;
	height: 200px; /* 和父容器高度相同 */
	font-size: 0;
}
</style>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值