1. 程式人生 > >59、div垂直居中和水平居中

59、div垂直居中和水平居中

1、高度固定的div在父元素中垂直居中情況(相對簡單些):

方法1:無副作用;相容性:IE8及以上

css:
.father{height: 300px;position: relative;background-color: green;}
.son{height: 100px;position: absolute;left: 0;right: 0;top: 0;bottom: 0;margin: auto 0;background-color: red;}

html:
<div class="father">
<div class="son"></div>
</div>

方法2:無副作用;相容性:IE6及以上

css:
.father{height: 300px;position: relative;background-color: green;}
.son{height: 100px;position: absolute;width: 100%;top: 50%;margin-top: -50px;background-color: red;}

html:
<div class="father">
<div class="son"></div>
</div>

**

2、高度不定(自適應)的div在父元素中垂直居中(這個情況稍微複雜些):

**
方法1:無副作用;相容性IE9及以上

css:
.father{height: 200px;width: 300px;background-color: green;}
.son{position: relative;top: 50%;transform: translateY(-50%);background-color: red;word-break: break-all;}

html:
<div class="father">
<div class="son">ssssssssssddddddddddddddd
ddddddssssssssssdddddddddddddddddddddss
ssssssssdddddddddddddddddddddssssssssssd
dddddddddddddddddddd</div
> </div>

方法2:有副作用(中間多了一層div);相容性IE6及以上

css:
.out{display: table;width: 300px;height: 200px;border: 1px solid #ddd;}
.mid{display: table-cell;vertical-align: middle;border: 1px solid green;}
.in{border: 1px solid red;}
/* 相容IE7 */
*+html .out{position: relative;text-align: center;}
*+html .mid{position: absolute;top: 50%;}
*+html .in{position: relative;top: -50%;left: -50%;}
/* 相容IE6(實測IE5.5也行) */
*html .out{position: relative;text-align: center;}
*html .mid{position: absolute;top: 50%;}
*html .in{position: relative;top: -50%;left: -50%;}

html:
<div class="out">
<div class="mid">
<div class="in">666dasdadasdadasdadasdasdasds
adsadsadasdsadsadsadsadasdsadsadsadasdasd
sassssssssssssssssssssssssssssssssssssssssss
</div>
</div>
</div>

方法3:無副作用,最簡單,但是相容性只能到IE10及以上

css:
.out{display: flex;align-items: center;justify-content: center;width: 300px;height: 200px;border: 1px solid #ddd;}

html:
<div class="out">
<div>aaaaaa</div>
</div>