CSS定位
2023-08-22 16:45:41 #CSS

absolute 和 relative 定位的依据

  • relative 依据自身定位
  • absolute 依据最近一层的定位元素(absolute、relative、fixed 或 html)定位

居中对齐的实现方式

水平居中

  • inline 元素:text-align: center;
  • block 元素:margin: 0 auto;
  • absolute 元素:left: 50%; margin-left: -(width/2);

垂直居中

  • inline 元素:line-height: (height);
  • absolute 元素:top: 50%; margin-top: -(height/2);

水平垂直居中

  • absolute 元素:top: 50%; left: 50%; transform: translate(-50%, -50%); (width/height 值可固定可不固定)
  • absolute 元素:top: 0; right: 0; bottom: 0; left: 0; margin: auto; (必须设置 width/height 值,值可固定可不固定)
  • flex 布局:display: flex; justify-content: center; align-items: center;
  • table 布局:(父元素:)display: table; (子元素:)display: table-cell; vertical-align: middle; text-align: center
1
2
3
4
5
6
7
8
9
10
11
12
<div class="container1">
<div class="item1">item 1</div>
</div>
<div class="container2">
<div class="item2">item 2</div>
</div>
<div class="container3">
<div class="item3">item 3</div>
</div>
<div class="container4">
<div class="item4"><span>item 4</span></div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
.container1, .container2, .container3, .container4 {
position: relative;
width: 1000px;
height: 200px;
margin: 10px auto;
background-color: #ccc;
}
.item1 {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 800px;
height: 100px;
margin: auto;
background-color: #666;
text-align: center;
line-height: 100px;
}
.item2 {
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -400px;
width: 800px;
height: 100px;
background-color: pink;
text-align: center;
line-height: 100px;
}
.item3 {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
top: 50%;
left: 50%;
width: 80%;
height: 50%;
background-color: lightblue;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
.item4 {
display: table;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 80%;
height: 50%;
margin: auto;
background-color: yellowgreen;
}
.item4 span {
display: table-cell;
text-align: center;
vertical-align: middle;
}

232216