每次面试都是知识收获的过程!
1、文本水平居中
1 <style type="text/css">
2 p {
3 width: 200px;
4 height: 200px;
5 border: 2px solid black;
6 text-align: center;
7 }
8 </style>
9
10 <p>水平居中</p>
效果:
2、文本垂直居中
1 <style type="text/css">
2 p {
3 width: 200px;
4 height: 200px;
5 border: 2px solid black;
6 text-align: center;
7 line-height: 200px;
8 }
9 </style>
10
11 <p>水平居中</p>
效果:
3、块元素水平
1 <style type="text/css">
2 p {
3 width: 200px;
4 height: 200px;
5 border: 2px solid black;
6 text-align: center;
7 line-height: 200px;
8 margin: 0 auto;
9 }
10 </style>
效果:
4、块元素垂直居中
1 //第1种方法
2 p {
3 position: absolute;
4 left: 50%;
5 top: 50%;
6 200px;
7 height: 200px;
8 border: 2px solid black;
9 text-align: center;
10 line-height: 200px;
11 margin: -100px 0 0 -100px;
12 }
13
14 //第2种方法
15 p {
16 position: absolute;
17 left: 50%;
18 top: 50%;
19 200px;
20 height: 200px;
21 border: 2px solid black;
22 text-align: center;
23 line-height: 200px;
24 transform: translate(-50%,-50%);
25 }
26
27 //第3种方法
28 p {
29 position: absolute;
30 200px;
31 height: 200px;
32 border: 2px solid black;
33 text-align: center;
34 line-height: 200px;
35 margin: auto;
36 left: 0;
37 top: 0;
38 right: 0;
39 bottom: 0;
40 }
41
42 //第4种方法
43 p {
44 200px;
45 height: 200px;
46 border: 1px solid black;
47 text-align: center;
48 line-height: 200px;
49 }
50 #div2 {
51 display: flex;
52 justify-content: center;
53 align-items: center;
54 }
55
56 <div id="div2">
57 <p>垂直居中</p>
58 </div>
效果: