饥人谷技术博客

CSS 元素垂直居中和水平居中的方法(转)

2016-03-16  本文已影响0人  种谔

水平居中

  1. 行内元素
    行内元素水平居中非常简单,设置属性"text-align:center;“即可。

2.块级元素
块级元素水平居中,设置属性"margin:0 auto;"
****注:里面关键的是后面的属性值auto,既"margin-left:auto"和"margin-right:auto"****

垂直居中

Line-Height Method

Paste_Image.png

<strong>适用范围:单行文本垂直居中</strong>

代码

html
<div id="parent">
<div id="child">Text here</div>
</div>

css

#child {
line-height: 200px;
}

垂直居中一张图片,代码如下:

html

<div id="parent">
<img src="image.png" alt="" />
</div>

css

#parent {
line-height: 200px;
}
#parent img {
vertical-align: middle;
}

****注:该方法的重点在于line-height的高度等于块级元素的内容框高度(一般都是指:height值)****

CSS Table Method###

Paste_Image.png

****适用范围:通用****

代码:
html

<div id="parent">
<div id="child">Content here</div>
</div>

css

#parent {
display: table;
}
#child {
display: table-cell;
vertical-align: middle;
}

低版本 IE fix bug:
#child {
display: inline-block;
}

****注:vertical-align:middle这个属性一般情况下只对行内元素生效,对块级元素只有table-cell生效。参考文章****

Absolute Positioning and Negative Margin

Paste_Image.png

****适用:块级元素 但在IE版本低于7时不能正常工作****

代码:

html

<div id="parent">
<div id="child">Content here</div>
</div>

css

#parent {
position: relative;
}
#child {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 50%;
height: 30%;
margin: auto;
}

Equal Top and Bottom Padding

Paste_Image.png

****适用:通用****

代码:
html
<div id="parent">
<div id="child">Content here</div>
</div>

css
#parent {
padding: 5% 0;
}
#child {
padding: 10% 0;
}

****注:用margin也可以做到同样的效果,但是必须注意下height的高度。****

Floater Div###

Paste_Image.png

****适用:通用。****

代码:

html

<div id="parent">
<div id="floater"></div>
<div id="child">Content here</div>
</div>

css

#parent {
height: 250px;
}
#floater {
float: left;
height: 50%;
width: 100%;
margin-bottom: -50px;
}
#child {
clear: both;
height: 100px;
}

以上就是六种方法,可以在实际的使用过程中合理选择,参考文章《vertical-centering》。

上一篇 下一篇

猜你喜欢

热点阅读