居中布局
- 水平居中
行内元素,比如文本,图片,水平居中是通过给父元素设置text-align:center来实现
定宽块状元素,通过设置左右margin值为auto来实现水平居中
.center{width:100px;height:100px;margin:0 auto; }
不定宽块状元素 元素
inline-block + text-align
inline-block:ie6,7不兼容,可用 inline,zoo=1模拟inline-block
<div class="parent">
<div class="child">demo<div></div>
<style>
.parent{
text-align: center;
}
.child{
display: inline-block;
*display:inline;
zoom:1;
}
</style>
float+position
.parent{
position: relative;
float:left;
left:50%;
}
.child{
position: relative;
left:-50%;
}
absolute + transform(ie9以上支持,适合移动端)
.parent{
position:relative;
}
.child{
position:absolute;
left:50%;
transform:translateX(-50%);
}
flex +justify-content(ie9+支持,适合移动端)
<style>
.parent{display:flex;justify-content:center}
</style>
<div class="parent">
<div class="child">demo</div>
</div>
2.垂直居中
定宽块状元素
height:100px;
line-height:100px;
3.水平,垂直居中
定宽块状元素
.center{
width:300px;
height:200px;
position:absolute;
left:50%;
top:50%;
margin:-100px 0 0 -150px;
}
这种方法,要让DIV水平和垂直居中,必需知道该DIV得宽度和高度,然后设置位置为绝对位置,距离页面窗口左边框和上边框的距离设置为50%,这个50%就是指页面窗口的宽度和高度的50%,最后将该DIV分别左移和上移,左移和上移的大小就是该DIV宽度和高度的一半。
不定宽块状元素
table-cell + vertical-align +text-align +inline-block
<div class="parent">
<div class="child">demo</div>
</div>
<style>
.parent{
text-align:center;
display:table-cell;
vertical-align:middle;
}
.child{
display:inline-block;
//ie6,7使用inline模拟inline-block
*display:inline;
zoom:1
}
</style>
absolute + transform
ie9以上支持,适合移动端
.parent{position:relative;}
.child{
position:absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%);
}
flex + justify-content+align-items
ie9以上支持,适合移动端
.parent{
display:flex;
justify-content:center;
align-items:center;
}