第一种:盒子宽高 + margin
- 思路 :上外边距为自身高度一半,左外边距为自身宽度一半:
.box {
width: 800px;
height: 400px;
border: 1px solid black;
}
.son {
width: 400px;
height: 200px;
margin-top: 100px; /* 上外边距为自身高度一半 */
margin-left: 200px; /* 左外边距为自身宽度一半 */
border: 1px solid red;
}
第二种:盒子高度 + margin
- 思路:让子盒子距离顶部外边距为自己高度的一半,左右auto
.box {
width: 800px;
height: 400px;
border: 1px solid black;
}
.son {
width: 400px;
height: 200px;
/* 让子盒子距离顶部外边距为自己高度的一半,左右auto */
margin: 100px auto;
border: 1px solid red;
}
第三种:盒子宽高 + 定位 + margin
- 思路 1 :给父盒子加相对定位,给子盒子加绝对定位,再设置子盒子相对于父盒子的边偏移:top:50%,left:50%;然后设置左外边距为自身宽度一半,上外边距为自身高度一半
.box {
position: relative;
width: 800px;
height: 400px;
border: 1px solid black;
}
.son {
position: absolute;
width: 400px;
height: 200px;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -200px;
border: 1px solid red;
}
- 思路 2 :将子盒子边偏移全部设置成0,然后使用margin:auto
.box {
position: relative;
width: 800px;
height: 400px;
border: 1px solid black;
}
.son {
position: absolute;
width: 400px;
height: 200px;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
border: 1px solid red;
}
第四种:定位 + Transform
- 思路:设置子盒子边偏移 top:50%,left:50%,再用CSS3属性transform: translate(-50%, -50%);
.box {
position: relative;
width: 800px;
height: 400px;
border: 1px solid black;
}
.son {
position: absolute;
width: 400px;
height: 200px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border: 1px solid red;
}
第五种:Felx
- 思路:
- justify-content:center;设置flex盒子中的项目在主轴上居中对齐
- align-items:center;设置flex盒子中的项目在侧轴和主轴上居中对齐
- 主轴和侧轴都居中了,盒子也就水平垂直居中了
.box {
display: flex;
justify-content: center; /* 设置flex盒子中的项目在主轴上居中对齐 */
align-items: center; /* 设置flex盒子中的项目在侧轴和主轴上居中对齐 */
width: 800px;
height: 400px;
border: 1px solid black;
}
.son {
width: 400px;
height: 200px;
border: 1px solid red;
}