一、水平垂直居中
block块级元素
1.绝对定位 + 负marin(居中元素宽高固定且已知)
HTML
<div class="box"> <div class="box-item"></div> </div>
CSS
.box { position: relative; width: 250px; height: 250px; border: 2px solid #000; } .box .box-item { position: absolute; width: 150px; height: 100px; left: 50%; top: 50%; margin-left: -75px; margin-top: -50px; background-color: #f40; }
结果展示
2. 绝对定位 + translate
HTML
<div class="box"> <div class="box-item">tranlate</div> </div>
CSS
.box { position: relative; width: 250px; height: 250px; border: 2px solid #000; } .box .box-item { position: absolute; width: 75px; height: 50px; left: 50%; top: 50%; transform: translate(-50%, -50%); background-color: #f40; }
结果展示~~~~
3. flex
HTML
<div class="box"> <div class="box-item">flex</div> </div>
CSS
.box { display: flex; width: 250px; height: 250px; border: 2px solid #000; justify-content: center; align-items: center; } .box .box-item { width: 75px; height: 50px; background-color: #f40; }
结果展示:
4. 定位 + 4个0 + magin:auto
HTML
<div class="box"> <div class="box-item">top/right/bottom/left</div> </div>
CSS
.box { position: relative; width: 250px; height: 250px; border: 2px solid #000; } .box .box-item { position: absolute; width: 75px; height: 50px; margin: auto; top: 0; right: 0; bottom: 0; left: 0; background-color: #f40; }
结果展示:
文本
1. 单行文本:text-align + line-height
HTML
<div class="box"> <span>我是文本~~我是文本~~</span> </div>
CSS
.box { width: 250px; height: 70px; border: 2px solid #000; text-align: center; line-height: 70px; }
结果展示:
2、多行文本:
HTML
<div class="box"> <span>我是文本~~我是文本~~我是文本~~我是文本~~我是文本~~我是文本~~我是文本~~我是文本~~</span> </div>
CSS
.box { display:table-cell; text-align:center; vertical-align: middle; width: 250px; height: 250px; border: 2px solid #000; }
结果展示:
-------- 待更新