借助display布局

  • 父元素开启display:flex布局,并设置justify-content:center主轴的空隙分布
    • 因为是单行,所以使用align-items:center设置侧轴上的对其方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<body>
<style>
.a{
width: 200px;
height: 200px;
background-color: red;
display: flex;
justify-content: center;
align-items: center;
}
.a .a1{
width: 50px;
height: 50px;
background-color: green;
}
</style>
<div class="a">
<div class="a1"></div>
</div>
</body>

借助flex布局

  • 啊啊啊
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<body>
<style>
.a{
width: 200px;
height: 200px;
background-color: red;
display: grid;
}
.a .a1{
width: 50px;
height: 50px;
background-color: green;
justify-self: center;
align-self: center;
}
</style>
<div class="a">
<div class="a1"></div>
</div>
</body>

借助绝对定位和盒子模型计算规则

  • 借助这一条规则
1
2
3
margin-left + border-left + padding-lef + width + padding-right + border-right + margin-right = 父元素内容区的宽度

高度和是一样的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<body>
<style>
.a{
width: 200px;
height: 200px;
background-color: red;
position: relative;
}
.a .a1{
width: 50px;
height: 50px;
background-color: green;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto ;
}
</style>
<div class="a">
<div class="a1"></div>
</div>
</body>

借助绝对定位和transform

  • top、left、right、bottom设置百分比基于父元素
  • translate的百分比参照自身
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<body>
<style>
.a{
width: 200px;
height: 200px;
background-color: red;
position: relative;
}
.a .a1{
width: 50px;
height: 50px;
background-color: green;
position: absolute;
top: 50%;
right: 50%;
left: 50%;
bottom: 50%;
transform: translate(-50%,-50%);
}
</style>
<div class="a">
<div class="a1"></div>
</div>
</body>