文章目录
  1. 1. 方式一: margin
  2. 2. 方式二: 定位 + margin
  3. 3. 方式三: 定位 + 变换
  4. 4. 方式四: 弹性布局

方式一: margin

基本思路:
1.子元素设置margin上下的值为:(父元素的高度 - 子元素的高度) / 2;
2.设置margin左右的值为:auto(浏览器自动计算外边距)。

css代码:

1
2
3
4
5
6
7
8
9
10
11
.parent{
width: 400px;
height: 400px;
border: 1px solid #000;
}
.child{
width: 100px;
height: 100px;
margin: 150px auto;
background-color: red;
}

HTML代码:

1
2
3
4
<!-- 以下样式全为此结构 -->
<div class="parent">
<div class="child"></div>
</div>

方式二: 定位 + margin

基本思路:
1.父元素设置相对定位;
2.子元素设置绝对定位(子绝父相);
3.子元素设置top值为50%(取父元素的高度),left值为50%(取父元素的宽度);
4.子元素设置margin:left值为负的自身宽度的一半,margin:top值为负的自身高度的一半;

css代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.parent{
position: relative;
width: 400px;
height: 400px;
border: 1px solid #000;
}
.child{
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
margin-left: -50px;
margin-top: -50px;
background-color: red;
}

方式三: 定位 + 变换

基本思路:
1.父元素设置相对定位;
2.子元素设置绝对定位;
3.子元素设置left:50%,top:50%;
4.子元素设置变换属性transform,平移translat在X轴方向和Y轴方向各移-50%(取自身宽高的50%);

css代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.parent{
position: relative;
width: 400px;
height: 400px;
border: 1px solid #000;
}
.child{
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
background-color: red;
/* 这里的50%,取的是自身的宽高 */
transform: translate(-50%,-50%);
}

方式四: 弹性布局

基本思路:
1.父元素开启弹性布局;
2.父元素设置子元素在主轴(默认为X轴)方向上的对其方式为居中;
3.父元素设置子元素在副轴(默认为Y轴)方向上的对其方式为居中;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.parent{
/* 开启弹性布局 */
display: flex;
/* 设置主轴居中(默认为X轴) */
justify-content: center;
/* 设置副轴居中(默认为Y轴) */
align-items: center;
width: 400px;
height: 400px;
border: 1px solid #000;
}
.child{
width: 100px;
height: 100px;
background-color: red;
}

写的不好的地方,望大家多多指正,小弟感激不尽!

文章目录
  1. 1. 方式一: margin
  2. 2. 方式二: 定位 + margin
  3. 3. 方式三: 定位 + 变换
  4. 4. 方式四: 弹性布局