<style>
/* 1、绝对定位+负margin值 */
.box {
/* 子绝父相 */
position: relative;
width: 200px;
height: 200px;
border: 1px solid red;
}
.childrenbox {
position: absolute;
width: 100px;
height: 100px;
background-color: yellow;
/* 先向下、向右移动父盒子高度和宽度的一半 */
top: 50%;
left: 50%;
/* 向上移动子盒子高度的一半;向左移动子盒子宽度的一半*/
margin-left: -50px;
margin-top: -50px;
}
/* 2、绝对定位+transform */
.box {
/* 子绝父相 */
position: relative;
width: 200px;
height: 200px;
border: 1px solid red;
}
.childrenbox {
position: absolute;
width: 100px;
height: 100px;
background-color: yellow;
/* 先向下、向右移动父盒子高度和宽度的一半 */
top: 50%;
left: 50%;
/* 向上移动子盒子高度的一半;向左移动子盒子宽度的一半*/
transform: translate(-50%, -50%);
}
/* 3、绝对定位+left/right/bottom/top+margin */
.box {
/* 子绝父相 */
position: relative;
width: 200px;
height: 200px;
border: 1px solid red;
}
.childrenbox {
position: absolute;
display: inline;
top: 0;
left: 0;
right: 0;
bottom: 0px;
background: yellow;
margin: auto;
height: 100px;
width: 100px;
}
/* 4、flex布局 */
.box {
display: flex;
width: 200px;
height: 200px;
border: 1px solid red;
justify-content: center;
align-items: center;
}
.childrenbox {
width: 100px;
height: 100px;
background: yellow;
}
/* 5、grid布局 */
.box {
display: grid;
width: 200px;
height: 200px;
border: 1px solid red;
}
.childrenbox {
width: 100px;
height: 100px;
background: yellow;
margin: auto;
}
/* 6、table-cell+vertical-align+inline-block/margin:auto */
.box {
display: table-cell;
width: 200px;
height: 200px;
border: 1px solid red;
text-align: center;
vertical-align: middle;
}
.childrenbox {
/* 可以换成margin:auto; */
display: inline-block;
width: 100px;
height: 100px;
background: yellow;
}
</style>
<body>
<div class="box">
<div class="childrenbox"></div>
</div>
</body>
CSS实现水平垂直居中
最新推荐文章于 2025-05-19 16:10:36 发布