1.代码部分
- 块级元素
<div class="parent">
<div class="child">child</div>
</div>
- 行内元素
<div class="parent">
<span class="child">child</span>
</div>
2.水平居中
- 行内元素居中 text-align:center;
.parent {
text-align: center;
}
- 块级元素 margin:auto;
低版本浏览器兼容需设置 text-align:center;
.parent {
text-align: center;
}
.child {
margin: auto;
border: 1px solid red;
}
3.垂直居中
1.行内元素(单行文字垂直居中) line-height=height
.parent {
height: 200px;
line-height: 200px;
border: 1px solid red;
}
2.块级元素:绝对定位+margin(需要提前知道其尺寸)
- 优点是兼容性好
- 缺点是需要提前知道其尺寸
.parent {
position: relative;
height: 200px;
}
.child {
width: 80px;
height: 40px;
background: blue;
position: absolute;
left: 50%;
top: 50%;
margin-top: -20px;
margin-left: -40px;
}
3.块级元素:绝对定位+transform
- 优点是不需要提前知道其尺寸
- 缺点是兼容性不好
.parent {
position: relative;
height: 200px;
}
.child {
width: 80px;
height: 40px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background: blue;
}
4.块级元素:绝对定位+margin: auto; (优先选用)
- 优点是不需要提前知道其尺寸,兼容性好
- 暂时未发现缺点
.parent {
position: relative;
height: 200px;
}
.child {
width: 80px;
height: 40px;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
background: blue;
}
5.块级元素:padding
- 缺点是如果高度固定,需要七天计算尺寸(只在某些特定情况下适用)
.parent {
padding: 5% 0;
}
.child {
padding: 10% 0;
background: blue;
}
6.块级元素:display: table-cell;
适用于多行文字居中处理
.parent {
width: 600px;
height: 200px;
border: 1px solid red;
display: table;
}
.child {
display: table-cell;
vertical-align: middle;
}
or
.parent {
height: 300px;
border: 1px solid red;
display: table-cell;
vertical-align: middle;
}
7.块级元素:display: flex;
缺点是兼容性不好
.parent {
width: 600px;
height: 200px;
border: 1px solid red;
display: flex;
align-items: center;
justify-content: center;/*水平居中*/
}
.child {
background: blue;
}
8.块级元素:伪元素
.parent {
width: 300px;
height: 300px;
border: 1px solid red;
text-align: center;
}
.child {
background: blue;
width: 100px;
height: 40px;
display: inline-block;
vertical-align: middle;
}
.parent::before {
content: "";
height: 100%;
display: inline-block;
vertical-align: middle;
}
9.块级元素:calc()
不推荐
缺点是兼容性差,需要使用calc
.parent {
width: 300px;
height: 300px;
border: 1px solid red;
position: relative;
}
.child {
width: 100px;
height: 100px;
bckground: blue;
padding: calc((100% - 100px)/2);
background-clip: content-box;
}
10.块级元素:display: inline-block;
html代码:
<div class="parent">
<div class="child">child</div>
<div class="brother">brother</div>
</div>
CSS代码:
.parent {
width: 400px;
height: 400px;
border: 1px solid red;
position: relative;
}
.child, .brother {
display: inline-block;
vertical-align: middle;
}
.child {
background: blue;
font-size: 12px;
}
.brother {
height: 400px;
font-size: 0;
}
11.table布局
不推荐,html中需要额外增加table等标签,冗余且改变了html结构
<table>
<tr>
<td align="center" valign="middle">content</td>
</tr>
</table>
网友评论