元素居中挑战

元素居中挑战

看看自己能写出多少种元素居中的方法,持续更新中

需要呈现的效果如下,宽高 500px 的正方形盒子里面居中拜访一个 200px 的盒子

Flex

把父元素变成弹性盒子,然后设置justify-content: center;align-items: center; 让子元素居中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.parent {
width: 500px;
height: 500px;
border: 1px solid black;
margin: 200px auto;
display: flex;
justify-content: center;
align-items: center;
}
.son {
border: 1px solid red;
width: 200px;
height: 200px;
}

Grid

Flex 一样

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.parent {
width: 500px;
height: 500px;
border: 1px solid black;
margin: 200px auto;
display: grid;
justify-content: center;
align-items: center;
}
.son {
border: 1px solid red;
width: 200px;
height: 200px;
}

定位 + translate

先通过父相子绝让 son 绝对定位,设置子元素的 topleft 的值为 50%(注意此时百分比的参照物是父元素),子元素左上角的点位于元素中间,在让子元素相对自身向左上各移动 50% transform: translate(-50%, -50%) (translate 的百分比参照自身)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
.parent {
width: 500px;
height: 500px;
border: 1px solid black;
margin: 200px auto;
position: relative;
}
.son {
border: 1px solid red;
width: 200px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
}

定位 + margin

子元素绝对定位,并且设置子的top left right bottom 均为 0,这其实是设置了子元素所占的空间位置,在设置 margin:auto 实现上下左右居中

参考:What does “top: 0; left: 0; bottom: 0; right: 0;” mean?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
.parent {
width: 500px;
height: 500px;
border: 1px solid black;
margin: 200px auto;
position: relative;
}
.son {
border: 1px solid red;
width: 200px;
height: 200px;
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}

calc() + margin 或者 定位

calc(50% - 子元素一半宽度(高度))可以的出居中所需宽高,其中calc中的百分数指的是相对于父元素的大小设定的比率

1
2
3
4
5
6
7
8
9
10
11
12
.parent {
width: 500px;
height: 500px;
border: 1px solid black;
margin: 200px auto;
}
.son {
border: 1px solid red;
width: 200px;
height: 200px;
margin: calc(50% - 100px);
}

伪元素 + inline-block + vertical-align

利用行内块元素 vertical-align: middle; 垂直中心对齐原理,伪元素宽度设为 0,实现视觉上只有一个元素。伪元素也可以用一个空盒子替代,与为了清除浮动创造一个空盒子的思想类似。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
.parent {
width: 500px;
height: 500px;
border: 1px solid black;
margin: 200px auto;
text-align: center;
}
.son {
border: 1px solid red;
width: 200px;
height: 200px;
vertical-align: middle;
display: inline-block;
}
.parent::after {
content: "";
width: 0px;
height: 100%;
vertical-align: middle;
display: inline-block;
}

暂时先这6种方法,以后想到了再补充 ~ ~


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!