码迷,mamicode.com
首页 > Web开发 > 详细

6 种CSS设置居中的方法

时间:2014-10-15 12:27:50      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   io   os   ar   for   

原文

Demos of each of the methods below by clicking here.

Horizontal centering with css is rather easy. When the element to be centered is an inline element we use text-align center on its parent. When the element is a block level element we give width and set the left and right margins to auto.

 

With text-align: center in mind, most people look first to vertical-align in order to center things vertically. 

Unfortunately vertical-align doesn’t apply to block-level elements like a paragraph inside a div, It applies to table cells and it works with some inline elements.

Line-Height Method

All we need to do is set a line-height on the element containing the text larger than its font-size.

<div id="parent">
    <div id="child">Text here</div>
</div>
#child {
    line-height: 200px;
}

The above works in all browsers, however it will only work for a single line of text. If your text could wrap to a 2nd line you need to use a different method. The value of 200px above is arbitrary. You can use any value you want as long as its larger than the font-size that’s been set.

Centering an Image with Line-Height

What if the content you want centered is an image? Will this method work? The answer is yes with one additional line of css.

CSS Table Method

Above I mentioned that vertical-align applies to table cells which leads us to this method. We’ll display our elements as table and table cell and then use the vertical-align property to center the content.

Note: CSS tables are not the same as html tables.

 

 

6 种CSS设置居中的方法

标签:des   style   blog   http   color   io   os   ar   for   

原文地址:http://www.cnblogs.com/shawnzxx/p/4025706.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!