CSS水平居中水平垂直居中
行内元素水平居中,对于如文本、span、a标签之类的,可以在其父元素上设置text-align:center。若子元素有块级元素且块级元素没有设置宽度,则也会水平居中。当父元素设置行高line-height等于父元素的高度,并设置 text-align: center;可实现行内元素水平垂直居中
<style>
.prent {
width: 600px;
height: 400px;
text-align: center;
border: 1px solid black;
}
.p1 {
height: 50px;
border: 1px solid red;
}
.box {
width: 100px;
height: 100px;
background-color: pink;
}
</style>
<div class="prent">
<span>name</span>
<a href="www.baidu.com">baidu</a>
行内元素水平居中
<p class="p1">
段落水平居中
</p>
<div class="box">
我是盒子
</div>
</div>
块级元素水平居中,对于块级元素可以设置margin: 0 auto(上下边距0,左右自动平分),来实现水平居中。使用margin:0 auto 其夫元素必须是块级元素,且有宽度
<style>
.container {
width: 400px;
height: 200px;
border: 1px solid red;
margin: 0 auto;
}
p {
width: 200px;
height: 50px;
border: 1px solid black;
margin: 0 auto;
text-align: center;
line-height: 50px;
}
</style>
<div class="container">
<p>
段落水平居中
</p>
</div>
这里设置行高line-height等于p的高度叠加 text-align: center;,可以实现行内标签或文本垂直居中
Flexbox 实现居中
justify-content: center; 是 Flexbox 布局中用于水平居中的关键属性。父容器设置为displey:flex变为弹性容器,所有子元素自动成为flex itme(弹性项目)。在该容器中,子元素自动排列为一行,宽度会自动收缩且不会换行。而justify-content: center 则是将这些子元素在水平方向居中排列。这样就可以实现所有子元素水平居中。
当父元素再设置align-items: center;时就可以达成水平垂直居中
<style>
.container {
width: 400px;
height: 200px;
background-color: pink;
display: flex;
justify-content: center;
}
.box {
width: 50px;
height: 50px;
background-color: red;
margin-left: 10px;
}
</style>
<div class="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
Grid 实现水平居中
Grid是css中的一种二维布局,
<style>
.container {
width: 600px;
height: 600px;
background-color: pink;
display: grid;
justify-content: center;
}
.box {
width: 50px;
height: 50px;
background-color: blue;
}
</style>
<div class="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
绝对定位实现水平垂直居中
<style>
.container {
width: 600px;
height: 300px;
background-color: pink;
position: relative;
}
.box {
width: 100px;
height: 100px;
position: absolute;
background: #000;
left: 50%;
top: 50%
transform: translateX(-50%);
}
</style>
<div class="container">
<div class="box"></div>
</div>
总结
1. Flexbox 法(推荐)
.parent {
display: flex;
align-items: center; /* 垂直居中 */
}
2. Grid 法
.parent {
display: grid;
align-items: center; /* 或 place-items: center */
}
3. 绝对定位 + transform
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
4. 表格单元格法
.parent {
display: table-cell;
vertical-align: middle;
}
5. line-height 法(单行文本)
.child {
line-height: 容器高度;
}
6. margin:auto 法(需已知尺寸)
.child {
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
height: 固定高度;
}