CSS实现元素水平垂直居中的几种方式
让不定宽元素垂直水平居中的几种方法
- grid
- flex
- position
- translate
演示环境
- 代码
- 用两个div作为父元素,实现子元素div的水平垂直居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box1,#box2 {
width: 300px;
height: 300px;
border: 1px solid black;
float: left;
margin: 20px;
}
.box1-1 {
background: lightblue;
width: 100px;
height: 100px;
}
.box2-1 {
background: lightpink;
width: 150px;
height: 200px;
}
</style>
</head>
<body>
<div id="box1">
<div class="box1-1"></div>
</div>
<div id="box2">
<div class="box2-1"></div>
</div>
</body>
</html>
- 如图所示,未实现效果:
- 如图所示,实现效果:
方式一:grid
在子元素上添加 margin: auto;我们可以发现子元素实现了水平居中,但在垂直方向还是无变化。
因此我们可以为父元素添加 Grid 网格布局,使得margin支持上下左右的居中。
#box1,#box2 {
display: grid;
}
.box1-1,.box2-1 {
margin: auto;
}
方式二:flex
使用弹性盒模型 flex,使得margin支持上下左右的居中。
#box1,#box2 {
display: flex;
}
.box1-1,.box2-1 {
margin: auto;
}
方式三:position
使用绝对定位,使得子元素脱离文档流。
通过设置左右,上下都为0,利用 margin: auto 居中两边等价的原理,实现最终的效果。
#box1,#box2 {
position: relative;
}
.box1-1,.box2-1 {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
方式四:translate
使用父相子绝的定位方式,让子元素距左,距顶偏移一半,此时子元素的左上角在父元素的中心点。
我们可以利用 CSS3的 transform属性将子元素向左上方,X轴,Y轴拉取50%。
#box1,#box2 {
position: relative;
}
.box1-1,.box2-1 {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}