CSS垂直居中对齐

用CSS有多种方法实现垂直居中对齐。如果已知外部div的高度,不管是否知道内部div的高度,垂直居中实现起来很简单,但如果内部div高度是变量,如文字,垂直居中实现起来就比较复杂了,很可能需要使用hacks。如:

<div id="containingBlock">
      <div><p>This sentence will change in each example</p> </div>
</div>

1、已知高度情况

很简单,直接计算就可以了

#containingBlock {display: block; height: 200px;}
#containingBlock div {height:50px; margin: 75px 0;}

2、通过display: table属性布局

通过使用 display: table;vertical-align: middle可以比较轻松的实现垂直居中,但IE6和IE7并不识别table和table-cell属性,必须使用hacks作为补充。

#containingBlock {display: table; height: 200px; position: relative; overflow: hidden;}
#containingBlock div {display: table-cell; vertical-align: middle;}

IE6和IE7的CSS

#containingBlock {height: 200px; position: relative; overflow: hidden;}
#containingBlock div { position: absolute; top: 50%;}
#containingBlock div p {position: relative; top: -50%;}

显示为

IE6和IE7的hack

//Vertical Alignment Table Display Hack
#containingBlock {display:table; height: 200px; position: relative; overflow: hidden; }
#containingBlock div {*position: absolute; top: 50%; display: table-cell; vertical-align: middle;}
#containingBlock p {*position: relative; top: -50%;}

补充: 如果想实现流式布局,加入如下CSS

html, body, #containingBlock {height: 100%; position:relative; }
#containingBlock div {height: 50%; position: absolute; top: 25%; }

3. 垂直居中所用到的参数

描述

length

Raises or lower an element by the specified length.

Negative values are allowed

%

Raises or lower an element in a percent of the “line-height”

property. Negative values are allowed

baseline

Align the baseline of the element with the baseline of the parent element.

This is default

sub

Aligns the element as it was subscript

super

Aligns the element as it was superscript

top

The top of the element is aligned with the top of the

tallest element on the line

text-top

The top of the element is aligned with the top of

the parent element’s font

middle

The element is placed in the middle of the parent element

bottom

The bottom of the element is aligned with the

lowest element on the line

text-bottom

The bottom of the element is aligned with the

bottom of the parent element’s font

inherit

Specifies that the value of the vertical-align property

should be inherited from the parent element

参考:Vertical Centering With CSS

 

转载于:https://www.cnblogs.com/JoannaQ/p/3601543.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值