常见布局方法总结
水平居中布局
(1) width: (xxx)px; margin: 0 auto;
使用场景:页面整体水平居中,有具体宽度要求。
<div class="wrap">
<div class="content"></div>
</div>
.content {
width:1000px;
height:100px;
background:red;
margin:0 auto;
}
(2) text-align: center; display: inline-block;
使用场景:子元素有多个且需要水平居中排列
<div class="wrap">
<div class="content"></div>
<div class="content"></div>
<div class="content"></div>
<div class="content"></div>
<div class="content"></div>
</div>
.wrap {
text-align: center;
}
.content {
display: inline-block;
width: 100px;
height: 100px;
background: red;
}
(3) absolute
+left:50%
+margin-left:-width/2
使用场景:子元素宽度确定,子元素之间互不影响
<div class="wrap">
<div class="content">
快过年了快过年了快过年了快过年了快过年了快过年了快过年了
</div>
</div>
.wrap {
position: relative;
}
.content {
position: absolute;
left: 50%;
width: 200px;
height: 100px;
margin-left: -100px;
background: red;
}
(4) absolute
+left:50%
+translateX(-50%)
使用场景:子元素宽度不确定,支持css3的translate
属性,子元素之间互不影响
<div class="wrap">
<div class="content">
快过年了快过年了快过年了快过年了快过年了快过年了快过年了
</div>
</div>
.wrap {
position: relative;
}
.content {
position: absolute;
left: 50%;
height: 100px;
background: red;
transform: translateX(-50%);
}
(5) flex
布局
使用场景: 支持flex
布局方式的浏览器都可以使用此布局,结合了(2)(4)两种方法的优点,无需考虑子元素宽度,且支持多个子元素居中
<div class="wrap">
<div class="content">
快过年了快过年了快过年了快过年了快过年了快过年了快过年了
</div>
</div>
.wrap {
display: flex;
justify-content: center;
}
.content {
height: 100px;
background: red;
}
垂直居中布局
相比水平居中布局,垂直居中稍微坑了一点,实现方法并没有灵活。
(1)table-cell
布局
使用场景:多行文字上下居中
<div class="wrap">
<div class="content">
快过年了快过年了快过年了快过年了快过年了快过年了快过年了
</div>
</div>
.wrap {
display: table-cell;
vertical-align: middle;
height: 200px;
}
.content {
width: 100px;
background: red;
}
(2)absolute
+top:50%
+margin-top:-height/2
使用场景:与水平居中一样,适用于子元素高度确定,不会对其他子元素造成影响的情况下的上下居中,由于是绝对定位,父元素需要占据空间,若没有其他子元素,需设置一个高度
.wrap {
position: relative;
height: 200px;
}
.content {
position: absolute;
top: 50%;
width: 300px;
height: 100px;
margin-top: -50px;
background: red;
}
(3) absolute
+top:50%
+translateY(-50%)
使用场景:与水平居中一样,适用于子元素高度不确定,不会对其他子元素造成影响的情况下的上下居中,由于是绝对定位,父元素需要占据空间,若没有其他子元素,需设置一个高度
.wrap {
position: relative;
height: 200px;
}
.content {
position: absolute;
top:50%;
background: red;
transform: translateY(-50%);
}
(4) flex
布局
使用场景: 支持flex
布局方式的浏览器都可以使用此布局,无需考虑子元素高度,书写简便快捷
<div class="wrap">
<div class="content">
快过年了快过年了快过年了快过年了快过年了快过年了快过年了
</div>
</div>
.wrap {
display: flex;
align-items: center;
height: 200px;
}
.content {
background: red;
}