案例一:子元素水平垂直居中
页面布局常遇见需要子元素完全居中显示,因此在此总结常见方案。
让黄色块在父容器(灰色块)中水平、垂直居中
黄色方块:宽高100px
灰色方块:宽高400px
下列方法1到方法7,变换前后的图像都是上面2张图(图标注了长度)
默认代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>完全居中</title>
<style>
.parent {
width: 400px;
height: 400px;
background-color: gray;
}
.children {
width: 100px;
height: 100px;
background-color: yellow;
}
</style>
</head>
<body>
<div class="parent">
<div class="children"></div>
</div>
</body>
</html>
下列方法1到方法7,里css代码都是基于上方默认代码
方法1:弹性布局+主/侧轴中间对齐
.parent {
/* 弹性布局 */
display: flex;
/* 主轴对齐方式:居中 */
justify-content: center;
/* 侧轴对齐方式(单行):居中 */
align-items: center;
}
方法2:弹性布局+margin自动
.parent {
/* 弹性布局 */
display: flex;
}
.children {
margin: auto;
}
方法3:定位(子绝父相)+margin
.parent {
position: relative;
}
.children {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
方法4:直接计算
分析过程:使用外边距推中间黄色盒子,距离顶端(400-100)/2= 150 px
.parent {
/* 因为margin塌陷问题(子容器的外边距会被父容器用掉):此处需要显示指明父容器溢出方式 */
overflow: auto;
}
.children {
/* 上下150px,左右自动 */
margin: 150px auto;
}
方法5: Transform属性
这种方法使用CSS的transform和position属性。这种方法在某些情况下可能比Flexbox或Grid更简单:
.children {
position: relative;
left: 50%;
top: 50%;
/*
transform:2/3D变换关键字
translate是2D位移关键字
x与y都-50%,是因为坐标原点默认是左上角,在left与top移动50%后,黄色盒子处于中心点右下方,因此需要让黄色盒子xy都减去一半
*/
transform: translate(-50%, -50%);
}
方法6:Grid布局
CSS Grid也是一个强大的布局工具,它也可以用来实现子元素的水平和垂直居中。以下是一个例子:
.parent {
display: grid;
justify-items: center;/* 水平居中 */
align-items: center;/* 垂直居中 */
}
方法7:使用表格布局
通过display设置为table-cell,然后使用text-align 、vertical-align实现水平居中和垂直居中。
.parent {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.children {
display: inline-block;
}
方法8:变化成行内块
若父元素宽高确定,子元素宽高不确定,用
将children设为行内元素,运用text-align即可实现水平居中,再借助vertical-align在垂直方向上达到居中效果。最后,将children的行高设定为默认值(line-height具有可继承性,需单独调整子元素的行高)。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>完全居中</title>
<style>
.parent {
width: 400px;
height: 400px;
background-color: gray;
text-align: center;
line-height: 400px;
}
.children {
background-color: yellow;
display: inline-block;
vertical-align: middle;
line-height: initial;
}
</style>
</head>
<body>
<div class="parent">
<div class="children">child</div>
</div>
</body>
</html>
更多精彩,请关注微信公众号:码圈小橙子