blog.csdn.net/freshlover/…css
水平居中
- 行内元素:text-align:center;
- flex布局:display:flex; justify-content:center;
- 经常使用(前提:已设置width值):margin-left:auto; margin-right:auto; margin:0 auto;
- 不定宽块状元素水平居中:改变块状元素的 dispaly 属性为 inline, 而后给父级设置 text-aline:center 来实现水平居中, 这种方法的缺点是不能再给元素设置宽高了
<div style="text-align: center;">
<div style="display: inline;">不定宽块状元素水平居中</div>
</div>
复制代码
垂直居中
* 行高:height:100px;line-height:100px; * table-cell:
html
<div class="box box1">
<span>垂直居中</span>
</div>
复制代码
css
.box1{
display: table-cell;
vertical-align: middle;
text-align: center;
}
复制代码
- flex布局:display: flex; justify-content:center; align-items:center;
水平垂直居中
- 方案1:position 元素已知宽度 父元素设置为:position: relative; 子元素设置为:position: absolute;距上50%,据左50%,而后减去元素自身宽度的距离就能够实现
html
<div class="box">
<div class="content">
</div>
</div>
复制代码
css
.box {
background-color:
width: 300px;
height: 300px;
position: relative;
}
.content {
background-color:
width: 100px;
height: 100px;
position: absolute;
left: 50%;
top: 50%;
margin: -50px 0 0 -50px;
}
复制代码
- 若是元素未知宽度,只需将上面例子中的margin: -50px 0 0 -50px;替换为:transform: translate(-50%,-50%);
- flex布局:display: flex; justify-content:center; align-items:center;
- 不知道本身高度和父容器高度的状况下, 利用绝对定位只须要如下三行:
css
parentElement{
position:relative;
}
childElement{
position: absolute;
top: 50%;
transform: translateY(-50%);
}
复制代码
- 若父容器下只有一个元素,且父元素设置了高度,则只须要使用相对定位便可
css
parentElement{
height:xxx;
}
.childElement {
position: relative;
top: 50%;
transform: translateY(-50%);
}
复制代码