CSS总结,六——元素的垂直居中

元素的垂直居中

1、已知高度宽度元素的水平垂直居中

① 绝对定位居中

.center{

margin:auto;

position:absolute;

top:0;

left:0;

bottom:0;

right:0;

}

② 绝对定位与负边距实现

.center{

width:100px;

height:100px;

position:absolute;

top:50%;

left:50%;

margin:-50px 0 0 -50px;

}

2、未知高度宽度元素的水平垂直居中

① 当元素为inline 或 inline-block时

#content {

display:table-cell; //表格单元格显示

text-align:center; //文本水平居中对齐

vertical-align:middle; //元素垂直居中对齐

}

#center{ }

② 利用css3的 transform

# content {

position:relative;

}

#center {

position:absolute;

top:50%;

left:50%;

transform:translate(-50%,-50%); //定义2D转换

}

③ 利用css3的 flex 布局 — CSS3 flex容器,所有子元素为容器成员(火狐、谷歌支持)

#content{

display:flex;

justify-content:center; //在主轴上居中对齐

align-items:center; //在交叉轴上居中对齐

}

#center{ }

ps:transform 和 flex 虽高效好用,但存在很多兼容问题。