不为别的,就是为了能信手拈来,所以整理了一份相关内容。
水平居中
- 如果水平居中元素为行内元素,设置父元素
text-align:center
; - 如果水平居中元素为块级固定,则需设置
margin: 0 auto
;(IE6下需在父元素上设置text-align: center;,再给子元素恢复需要的值)
<body>
<div class="content">
测试数据 测试数据 测试数据
测试数据 测试数据 测试数据
测试数据 测试数据 测试数据
测试数据 测试数据 测试数据...
</div>
</body>
<style>
body {
background: #DDD;
text-align: center;
}
.content {
width: 500px;
text-align: left;
margin: 0 auto;
background: orange;
}
</style>
- 如果元素为绝对定位,法一:设置父元素position为relative,元素设
left:0;right:0;margin:auto;
body{
background: #DDD;
}
.content{
width: 500px;
background: orange;
position: absolute;
left: 0;
right: 0;
margin:0 auto;
}
法二:设置父元素position为relative,子元素设置left和负值的margin-left;
body {
background: #DDD;
}
.content {
width: 500px;
background: orange;
position: absolute;
left: 50%;
margin-left: -250px;
}
- 如果元素为浮动,该元素设置
position: relative
, 并且浮动方向偏移量(left或者right)设置为50%,浮动方向上的margin设置为元素宽度一半乘以-1
body{
background: #DDD;
}
.content{
width: 500px;
background: orange;
float: left;
position: relative;
left: 50%;
margin-left: -250px;
}
- 使用flex-box布局,父元素指定justify-content属性为center;
body {
justify-content: center;
display: flex;
}
.content {
width: 500px;
}
垂直居中
- 若元素为单行:可设置line-height;
- 若元素是行内块级元素,display: inline-block, vertical-align: middle和一个伪元素让内容块处于容器中央(注:该方法指针对不折行的子元素)。
body::after, .content{
display: inline-block;
vertical-align: middle;
}
body::after{
content: '';
height: 100%;
}
body {
height: 200px;
}
- 将显示方式设置为表格,display:table-cell,同时设置vertial-align:middle;
body {
display: table;
width: 100%;
height: 200px;
}
.content {
display: table-cell;
vertical-align: middle;
border: 1px solid #666;
}
- 使用flex布局,设置为align-item:center;
body {
display: flex;
align-items: center;
width: 100%;
height: 200px;
border: 1px solid #666;
}
- 如果元素为绝对定位,法一:子元素中设置bottom:0,top:0,并设置margin:auto;
body {
background: #DDD;
}
.content {
width: 500px;
height: 200px;
background: orange;
position: absolute;
bottom: 0;
top: 0;
margin: auto 0;
}
法二:子元素设置top:50%,margin-top值为高度一半的负值;
body {
background: #DDD;
}
.content {
width: 500px;
height: 200px;
background: orange;
position: absolute;
top: 50%;
margin-top: -100px;
}