【css】盒子水平垂直居中的实现
一 HTML模板
先给出接下来用于测试的HTML模板
<style>
.parent {
width: 200px;
height: 200px;
background-color: skyblue;
}
.child {
width: 100px;
height: 100px;
background-color: pink;
}
</style>
</head>
<body>
<div class='parent'>
<div class='child'></div>
</div>
</body>
二 利用绝对定位
2.1 translate调整
- 利用绝对定位,先将元素的左上角通过
top:50%
和left:50%
定位到页面的中心。 - 然后再通过
translate
来调整元素的中心点到页面的中心。 - 该方法需要考虑浏览器兼容问题。
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
2.2 margin设置为auto
- 利用绝对定位,设置四个方向的值都为0,并将
margin
设置为auto
。 - 由于宽高固定,因此对应方向实现平分,可以实现水平和垂直方向上的居中。
- 该方法适用于盒子有宽高的情况。
.parent {
position: relative;
}
.child {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
2.3 margin负值调整
- 利用绝对定位,先将元素的左上角通过
top:50%
和left:50%
定位到页面的中心。 - 然后再通过margin负值来调整元素的中心点到页面的中心。
- 该方法适用于盒子宽高已知的情况
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px; /* 自身 height 的一半 */
margin-left: -50px; /* 自身 width 的一半 */
}
三 利用flex布局
- 使用flex布局,通过
align-items:center
和justify-content:center
设置容器的垂直和水平方向上为居中对齐。 - 然后它的子元素也可以实现垂直和水平的居中。
- 该方法要考虑兼容的问题,该方法在移动端用的较多。
注:
- 在flex弹性布局中,容器默认存在两根轴:水平的主轴(main axis)和垂直的交叉轴(cross axis),项目默认沿水平主轴排列。
align-items:center
和justify-content:center
设置容器的侧轴和主轴方向上为居中对齐。- 默认沿水平主轴排列,也可以设置垂直方向为主轴。
.parent {
display: flex;
justify-content:center;
align-items:center;
}
四 利用JS动态设置
<body>
<div class='parent' id="parent">
<div class='child' id="child"></div>
</div>
<script>
let parent = document.getElementById('parent');
let child = document.getElementById('child');
let parentWidth = parent.offsetWidth;
let parentHeight = parent.offsetHeight;
let childWidth = child.offsetWidth;
let childHeight = child.offsetHeight;
parent.style.position = "relative"
child.style.position = "absolute";
child.style.left = (parentWidth - childWidth) / 2 + 'px';
child.style.top = (parentHeight - childHeight) / 2 + 'px';
</script>
</body>