一、垂直居中:单行的行内元素解决方案
居中元素:单行的行内元素,即inline或者inline-*类型元素,如文字、链接等
解决方案:将该行内元素的height、inline-height设置为其父元素的高度
HTML
<
div
id
=”container”
>
<
a
href
=”#”
>hello,gbtags.comhello,gbtags.comhello,gbtags.com
</
a
>
</
div
>
CSS
#container {
background:
#222;
height:
200px;
}
a {
/*
height: 200px;
*/
line-height:
200px;
color:
#fff;
}
二、垂直居中:多行的行内元素解决方案
居中元素:多行的行内元素
解决方案:组合使用display:table-cell和vertical-align:middle属性来定义需要居中元素的父元素
HTML
<
div
id
=”container”
>
<
a
href
=”#”
>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reiciendis blanditiis optio accusamus quia sapiente at labore consectetur in quasi veritatis possimus quod nihil aliquam vero saepe rem quas. Ratione eligendi!
</
a
>
</
div
>
CSS
#container {
width:
300px;
height:
300px;
background:
#222;
/*
以下属性垂直居中
*/
display:
table-cell;
vertical-align:
middle;
}
a {
color:
#fff;
}
三、垂直居中:已知高度的块状元素解决方案
居中元素:块级元素,如div
解决方案:将待居中元素设置为绝对定位,并将其margin-top值设置为待居中元素高度的一半的负值。
HTML
<
div
class
=”item”
>
</
div
>
CSS
div {
width:
100px;
height:
100px;
background:
#222;
}
/*
以下为居中代码
*/
.item {
position:
absolute;
top:
50%;
margin-top:
-50px;
padding:
0;
/*
如果有padding设置,相对计算下margin-top的值
*/
}
四、垂直居中:未知高度的块状元素解决方案
居中元素:块级元素,如div,但不知其高度
解决方案:使用CSS3的transform属性
HTML
<
div
class
=”item”
>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet sint repellendus ab aut quisquam eligendi est in deleniti.
</
div
>
CSS
div {
width:
150px;
background:
#222;
color:
#fff;
}
/*
以下为居中代码
*/
.item {
position:
absolute;
top:
50%;
transform:
translateY(-50%);
}
五、水平垂直居中:已知宽度和高度的元素解决方案
居中类型:垂直和水平同时居中(前提是知道元素的高度和宽度)
解决方案:设置元素 绝对定位,并设置margin-top(高度/2)和margin-left值为(宽度/2)的负值
HTML
<
div
class
=”item”
>
</
div
>
CSS
div {
width:
150px;
height:
250px;
background:
#222;
color:
#fff;
}
/*
以下为居中代码
*/
.item {
position:
absolute;
top:
50%;
left:
50%;
margin-top:
-125px;
margin-left:
-75px;
}
六、水平垂直居中:未知元素高度和宽度的解决方案
居中类型:水平和垂直居中(前提是该元素的宽度和高度未知)
解决方案:设置该元素为绝对定位,并且使用CSS3的transform属性
HTML
<
div
class
=”item”
>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cupiditate nostrum quaerat debitis.
</
div
>
CSS
div {
background:
#222;
color:
#fff;
}
/*
以下为居中代码
*/
.item {
position:
absolute;
top:
50%;
left:
50%;
transform:
translate(-50%,-50%);
}
七、水平垂直居中:使用flex布局实现
解决方案:设置flex布局,并设置居中元素父元素的justify-content和align-items属性为center
HTML
<
div
class
=”parent”
>
<
div
class
=”item”
></
div
>
</
div
>
CSS
.item {
width: 100px;
height: 100px;
background: #
222;
}
/*
以下为居中代码
*/
.parent {
display: flex;
justify-content: center;
align-items: center;
/*
需要设置height查看垂直居中效果
*/
background: #ccc;
height: 300px;
}