title | date | tags | categories |
---|---|---|---|
老生常谈,关于元素居中 |
2017-10-19 07:08:17 -0700 |
Css |
Css |
在元素居中的这个问题上,已经是个老生常谈的问题了。其实,说来说去无外乎那么几种,这次好好地做个总结。
以下是我们给的两个div,以及默认样式:
<div class="dad">
<div class="son"></div>
</div>
.dad{
background-color: #eee;
width: 500px;
height: 300px;
}
.son{
background-color: red;
width: 100%;
height: 100px;
}
当我们使子元素距离父元素50%的时候,我们还要给子元素负位移回自身高度50%
.dad{
position: relative;
}
.son{
position: absolute;
top: 50%;
transform: translateY(-50%);
}
这种方法对子元素仅需要一个约束就是为行内块,而父元素需要需要变成表格以及垂直对齐。
.dad{
display: table-cell;
vertical-align: middle;
}
.son{
display: inline-block;
}
这一种使用了比较新的flex布局,仅需要对父元素flex和垂直对齐即可。这个以后要好好整理一遍。
.dad{
display: flex;
align-items: center;
}
我们这次把子元素宽带调为父80%,实现水平居中。
.dad{
background-color: #eee;
width: 500px;
height: 300px;
}
.son{
background-color: red;
width: 100%;
height: 100px;
}
方便快捷的margin左右auto
.son{
margin: 0 auto;
}
就像使文字居中那样,使行内块居中
.dad{
text-align: center;
}
.son{
display: inline-block;
}
同样的道理,flex的水平居中。😌不考虑兼容,使用flex真实爽啊!
.dad{
display:flex;
justify-content:center;
}
总结了这几种比较常用的,再想到再添加上去。 垂直:
absolute + transform
inline-block + table-cell + vertical-align
flex + align-items: center
水平:
margin: 0 auto
text-align: center + inline-block
flex + justify-content:center