Blog

It's a Wonderful Life

如何利用CSS实现元素的水平居中

2016-12-02 18:21 Posted in Learn with CSS , HTML

把以下代码复制到父元素的CSS样式代码中。

# {
    display: -webkit-box;
    -webkit-box-orient: horizontal;
    -webkit-box-pack: center;
    -webkit-box-align: center;
    display: -moz-box;
    -moz-box-orient: horizontal;
    -moz-box-pack: center;
    -moz-box-align: center;
    display: -o-box;
    -o-box-orient: horizontal;
    -o-box-pack: center;
    -o-box-align: center;
    display: -ms-box;
    -ms-box-orient: horizontal;
    -ms-box-pack: center;
    -ms-box-align: center;
    display: box;
    box-orient: horizontal;
    box-pack: center;
    box-align: center;
  }

2017/1/23更新

其实不用这么麻烦,display有个很好用的property叫做flex,使用它便能很好地实现元素在父元素中居中对齐。

flex	Displays an element as an block-level flex container. New in CSS3

flex是CSS3中新加入的属性,与flex-direction配合使用可达到很好的排版效果。w3详细解释如下:

flex-direction: row|row-reverse|column|column-reverse|initial|inherit;
Value Description
row Default value. The flexible items are displayed horizontally, as a row
row-reverse Same as row, but in reverse order
column The flexible items are displayed vertically, as a column
column-reverse Same as column, but in reverse order
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

举个例子:

# {
	display: flex;
	flex-direction: column /*make it positioned in middle-left*/
	text-align: center /*make it positioned in center*/
	
	/*or, without specifing text-align property, you can do this:*/
	&.# {
		margin: 0 auto;
	}
}