垂直居中

CSS:垂直居中

1、子元素为单行内联元素(父元素高度确定的单行文本):设置父元素的height等于line-height

*{
	margin:0;
	padding:0;
	list-style:none;
}
#wrap{
	height:27px;
	line-height:27px;
	background-color:#36F;
}
<div id="wrap">垂直居中</div>

优点:适用于所有浏览器

缺点:只对文本有效,块级元素是无效的。当文本内容的长度大于大于块的宽时,就会有内容脱离了块。

2、

子元素为多行内联元素:一、设置父元素的display:table-cell,并设置vertical-align:middle;

*{
	margin:0;
	padding:0;
	list-style:none;
}
#wrap{
	display:table;
}
#box{
	display:table-cell;
	vertical-align:middle;
	background-color:#36F;
	height:50px;
}
<div id="wrap">
    <div id="box">
      <div class="content">垂直居中<br/>垂直居中</div>
    </div>
</div>

优点:content里可以动态改变高度

二、使用table(tbody,tr,td),设置vertical-align:middle;

table td{
		height:500px;
		background:red;
}
<table>
        <tbody>
            <tr>
                <td>
                    <div>
                        <p>我要垂直居中</p>
                    </div>
                </td>
            </tr>
        </tbody>
</table>
注:td标签默认就设置了vertical-align:middle;
3、块级元素:使用position:absolute;top:0;bottom:0;margin:auto;

*{
	margin:0;
	padding:0;
	list-style:none;
}
.content{
	position:absolute;
	top:0;
	bottom:0;
	background-color:#09F;
	margin:auto;
	height:500px;
	width:70%;
        left:0;
        right:0;
        overflow:hidden;
}
<div class="content">垂直居中</div>

注:最好加上overflow:hidden;防止溢出。高度必须定义。

4、方法:使用绝对定位,把top设置为50%;margin-top设置为负的content高度的一半

*{
	margin:0;
	padding:0;
	list-style:none;
}
.content{
    position: absolute;
    top:50%;
    height:240px;
    margin-top:-120px;
    background-color:red;
}
<div class="content">垂直居中</div>  

注:高度必须定义。content是相对于浏览器来说。如果content外面包裹上一层div,则那个div要设置position:relative;

5、应用flex布局,给父元素设置display:flex;align-items:center;

*{
	margin:0;
	padding:0;
	list-style:none;
}
.content{
    display:flex;
	align-items:center;
	background-color:red;
	height:50px;
}
<div class="content">垂直居中</div>  





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值