使子盒子水平垂直居中的九种方法
初始化页面
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>使盒子水平垂直居中的方法</title>
<link rel="stylesheet" href="./index.css">
</head>
<body>
<!-- 使盒子水平居中,垂直居中 -->
<div class="box">
<div class="son"></div>
</div>
</body>
</html>
我使用的是 外联样式表
html,
body {
margin: 0;
padding: 0;
}
.box {
width: 400px;
height: 400px;
background-color: hotpink;
}
.son {
width: 200px;
height: 200px;
background-color: aqua;
}
第一种: 使父盒子转为table-cell, 也就是使父元素作为表格单元格来显示,子盒子转为行内块元素
.box {
display: table-cell;
/* 子元素水平居中 */
text-align: center;
/* 子元素中线对齐 */
vertical-align: middle;
}
.son {
display: inline-block;
/* 把子元素放置在父元素的中部 */
vertical-align: middle;
}
第二种: 子绝父相,这里有很多种方法 —2.1 margin:auto
.box {
position: relative;
}
.son {
position: absolute;
/* margin:auto 这部分上下偏移值设置为设为相同的像素值,左右设置为100px以内的相同像素值都可, 可以试试 */
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
第二种: 2.2 子盒子 定位后: top: 200px; margin-top: -100px; left: 200px; margin-left: -100px
.box {
position: relative;
}
.son {
position: absolute;
/* 绝对定位后, 上偏移父盒子的高度的50% */
top: 50%;
/* 上外边距为自身高度的负值一半 (因为要往上走) */
margin-top: -100px;
/* 绝对定位后, 左偏移父盒子的宽度的50% */
left: 50%;
/* 左外边距为自身宽度的负值一半 (因为要往左走) */
margin-left: -100px;
}
第二种: 2.3 子盒子 平移
.box {position: relative;
}
.son {
position: absolute;
/* 定位后 top: 50% left: 50% 元素会落在父盒子的右下角 */
top: 50%;
left: 50%;
/* 使用 2D 平移 X轴 Y轴 各自平移自身宽高的50% */
transform: translate(-50%, -50%);
}
第三种 : 利用margin
.box {
/* 注意这里要解决外边距塌陷的问题 */
overflow: hidden;
}
.son {
/* 目前我给的父盒子宽高正好都是整数400px,减去子盒子的宽高,除以2 即可, 实际应用的话测量多少给多少也可以 */
margin: 100px auto;
}
第四种 : 利用padding
.box {
/* 利用padding的话,要注意盒子模型,padding会撑大盒子,因此要减去padding值,重新设置宽高 */
width: 300px;
height: 300px;
padding-top: 100px;
padding-left: 100px;
}
第五种 : 利用flex 布局
.box {
/* flex 布局 就很简单了, 不需要计算, center center 即可 */
display: flex;
justify-content: center;
align-items: center;
}
第六种 : 利用 text-align: center; + margin-top
.box {
/* 这个也很好理解了 转行内块后,使用 text-align: center; */
text-align: center;
}
.son {
display: inline-block;
/* 再加上 外边距 挤一挤 大功告成*/
margin-top: 100px;
}
好啦 🤣🤣🤣, 写到这里就结束了, 欢迎大家批评指正,共勉咯🤜 !