父盒子和子盒子的结构
<div class="parent_box">
<div class="sub_box"></div>
</div>
父盒子和子盒子初始的样式
.parent_box {
width: 500px;
height: 500px;
margin: 100px auto;
border: 2px solid #000;
}
.sub_box {
width: 100px;
height: 100px;
background-color: yellow;
}
父盒子和子盒子初始效果
方法一:position + margin(元素已知宽度)
.parent_box {
position: relative; /* 给父盒子设置相对定位 */
width: 500px;
height: 500px;
margin: 100px auto;
border: 2px solid #000;
}
.sub_box {
position: absolute; /* 给子盒子设置绝对定位 */
top: 50%; /* 距离顶部设置 50% */
left: 50%; /* 距离左侧设置 50% */
width: 100px;
height: 100px;
margin-top: -50px; /* 减去高度自身一半 */
margin-left: -50px; /* 减去宽度自身一半 */
background-color: yellow;
}
方法二:position + transform (元素未知或已知高度都适合)
.parent_box {
position: relative; /* 给父盒子设置相对定位 */
width: 500px;
height: 500px;
margin: 50px auto;
border: 2px solid #000;
}
.sub_box {
position: absolute; /* 给子盒子设置绝对定位 */
left: 50%; /* 距离顶部设置 50% */
top: 50%; /* 距离左侧设置 50% */
width: 100px;
height: 100px;
transform: translate(-50%, -50%); /* 子盒子向上移动本身高度一半,向左移动本身宽度一半 */
background-color: yellow;
}
方法三:margin + calc (元素已知宽度)
.parent_box {
width: 500px;
height: 500px;
margin: 100px auto;
border: 2px solid #000;
}
.sub_box {
width: 100px;
height: 100px;
margin: calc(50% - 50px) auto;/* 利用 父盒子的一半,通过 calc的50% 减去本身的一半 */
background-color: yellow;
}
方法四:display:flex(弹性布局)(元素未知或已知高度都适合)
.parent_box {
display: flex; /* 给父盒子设置 flex属性 */
width: 500px;
height: 500px;
margin: 50px auto;
align-items: center; /* 给父盒子设置 垂直的交叉轴 居中 */
justify-content: center; /* 给父盒子设置 水平的主轴 居中 */
border: 2px solid #000;
}
.sub_box {
width: 100px;
height: 100px;
background-color: yellow;
}
实现效果