首页 > 代码库 > 6 种CSS设置居中的方法

6 种CSS设置居中的方法

原文

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设置居中的方法