CSS vertically centered

There are many ways to achieve with CSS vertically centered. If you know the height of the external div, whether or not know the height of the internal div, vertical centering is simple to implement, but if the internal div height is variable, such as text, centered vertically is more complicated to implement, it may be necessary to use hacks. Such as:

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

1, a known height situation

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

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

2, the display: table layout attributes

By using display: table;and vertical-align: middlecan be relatively easily realized vertically centered, but does not recognize IE6 and IE7 table and table-cell properties, hacks must be used as a supplement.

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

IE6 and IE7's CSS

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

shown as

IE6 and IE7's 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%;}

NOTE: If you want to achieve flow layout, add the following 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

Guess you like

Origin blog.csdn.net/weixin_34146805/article/details/93057191