块级元素居中 html代码部分
<div class="parent">
<div class="child">child</div>
</div>
行内元素居中 html代码部分
<div class="parent">
<span class="child">child</span>
</div>
水平居中
行内元素 text-align: center;
.parent {
text-align: center;
}
块级元素 margin: auto;
(低版本浏览器还需要设置 text-align: center;)
.parent {
text-align: center;
}
.child {
width: 100px;
margin: auto;
border: 1px solid blue;
}
垂直居中
行内元素(单行文字垂直居中):设置 line-height = height
.parent {
height: 200px;
line-height: 200px;
border: 1px solid red;
}
块级元素:绝对定位(已知宽高)
.parent {
position: relative;
height: 200px;
border: 1px solid #000;
}
.child {
width: 80px;
height: 40px;
background: #333;
position: absolute;
left: 50%;
top: 50%;
margin-top: -20px;
margin-left: -40px;
}
块级元素:绝对定位 + transform
优点:不需要提前知道尺寸
缺点:兼容性不好
.parent {
position: relative;
height: 200px;
border: 1px solid #000;
}
.child {
width: 80px;
height: 40px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
border: 1px solid #000;
}
块级元素:绝对定位 + margin: auto;
.parent {
position: relative;
height: 200px;
border: 1px solid #000;
}
.child {
width: 80px;
height: 40px;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
border: 1px solid #000;
}
块级元素:padding
如果高度固定,需要提前计算尺寸(只在某些特定情况适用)
.parent {
padding: 5% 0;
}
.child {
padding: 10% 0;
border: 1px solid #000;
}
块级元素:display: table-cell
.parent {
width: 600px;
height: 200px;
border: 1px solid #000;
display: table;
}
.child {
display: table-cell;
vertical-align: middle;
}
或者
.parent {
height: 200px;
border: 1px solid #000;
display: table-cell;
vertical-align: middle;
}
块级元素:display: flex
.parent {
width: 400px;
height: 200px;
border: 1px solid #000;
display: flex;
align-items: center;
justify-content: center; /*水平居中*/
}
.child {
border: 1px solid #000;
}
块级元素:伪元素
.parent {
width: 300px;
height: 300px;
border: 1px solid #000;
text-align: center;
}
.child {
border: 1px solid #000;
width: 100px;
height: 40px;
display: inline-block;
vertical-align: middle;
}
.parent::before {
content: '';
height: 100%;
display: inline-block;
vertical-align: middle;
}
块级元素:calc()
.parent {
width: 200px;
height: 200px;
border: 1px solid #000;
position: relative;
}
.child {
width: 100px;
height: 100px;
background: #000;
padding: -webkit-calc((100% - 100px) / 2);
padding: -moz-calc((100% - 100px) / 2);
padding: -ms-calc((100% - 100px) / 2);
padding: calc((100% - 100px) / 2);
background-clip: content-box;
}
}
这样基本上所有的水平居中和垂直居中就归纳好了。