前言
前端面试CSS必考题--居中
小编遇到这个问题的时候在各大网站搜索发现,每篇文章都有自己的独特的一两种方案,于是小编便决定整合一篇CSS居中解决方案,集中所有方案,方便大家面试前学习和复习。
能适用于不定宽高的方法一定适用于定宽高的情况
先来看一段初始代码
样式:
.parent{
width: 400px;
height: 400px;
background: rgb(212, 72, 182);
}
.child{
width: 100px;
height: 100px;
background: rgb(219, 228, 95);
}
盒子:
<div class="parent">
<div class="child"></div>
</div>
父容器parent ,子容器child,分别给上宽高和背景颜色
水平居中
1.(行内) text-align
.parent {
text-align: center;
}
2. flex
.parent {
display: flex;
justify-content: center;
}
3. margin
.child {
margin: 0 auto;
}
4. position + transform
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
5. grid
.parent {
display: grid;
}
.child {
justify-self: center;
}
6. (定宽高) position + margin
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%;
margin-left: -50px;
}
7. text-align + inline-block
.parent {
text-align: center;
}
.child {
display: inline-block;
}
垂直居中
1. (定宽高) position + margin-top
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
margin-top: -50px;
}
2. position + transform
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
3. position + margin
.parent {
position: relative;
}
.child {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto 0;
}
4. flex
.parent {
display: flex;
align-items: center;
}
5. gird
.parent {
display: grid;
}
.child {
align-self: center;
}
6. (行内) line-height
.child {
line-height: 400px;
}
7. table-cell + vertical-align
.parent {
display: table-cell;
vertical-align: middle;
}
8. (行内) ::after
.parent::after{
content: '';
height: 100%;
display: inline-block;
vertical-align: middle;
}
9. (行内) writing-mode + text-align
.parent{
text-align: center;
writing-mode: vertical-lr;
}
水平垂直居中
这边就列举一些常见的,其他的可在上文中进行组合使用
1. flex
.parent{
display: flex;
align-items: center;
justify-content: center;
}
2. gird
.parent {
display: grid;
}
.child {
align-self: center;
justify-self: center;
}
3. position + margin
.parent {
position: relative;
}
.child {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
4. (定宽高) position + margin-top & -left
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
margin: -50px 0 0 -50px;
}
5. position + transform
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
6. (行内) vertical-align + 伪元素
.parent {
text-align: center;
}
.parent::after{
content: '';
height: 100%;
display: inline-block;
vertical-align: middle;
}
7. table-cell + vertical-align
此方法同样适用于行内元素,去掉子容器中的inline-block即可
.parent {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.child {
display: inline-block;
}
8. (行内) writing-mode
.parent {
text-align: center;
writing-mode: vertical-lr;
}
.child {
writing-mode: horizontal-tb;
}
本期内容绝对的面试精华,各位看官可以点个赞或者收藏备用~下期见