CSS实现『垂直居中』的方式
一. 单行文本垂直居中
1️⃣. 使line-height
的值等于height
的值

height: 45px;
line-height: 45px;
2️⃣. 使padding-top
的值等于padding-bottom
的值,容器高度不固定,由内容撑开(没有明确要求最好不要设置高度
)
padding-top等于padding-bottom 单行文本对齐

padding-top: 20px;
padding-bottom: 20px;
二. flex实现绝对完美居中
适用于PC与移动端布局

给容器添加:
.container {
display: flex;
justify-content: center;
align-items: center;
}
三. position: absolute;
绝对定位实现垂直居中
1️⃣ 固定宽高
①
position: absolute; margin: auto; left: 0; top: 0; bottom: 0; right: 0;垂直容器居中对齐定宽高
position: absolute; margin: auto; ...

position: absolute;
width: 300px;
height: 300px;
margin: auto;
top: 0;
left: 0;
bottom: 0;
right: 0;
②
position: absolute;
负marginleft: 50%;
right: 50%;` 绝对定位垂直居中『定宽高』

position: absolute;
left:50%;
top:50%;
margin-left: -125px;
margin-top: -100px;
2️⃣ 宽高不定
position: absolute; transform: translate
『不定宽高』垂直居中
绝对定位宽高不定绝对居中transform: translate

四. vertical-align: center;
实现垂直居中
❗️vertical-align: center;
只适用于『行级元素』与td
table-cell
vertical-align: middle; 伪元素 图片在容器中居中①
vertical-align: middle; 图片在容器中居中②

.box::before {
content: '';
height: 100%;
display: inline-block;
vertical-align: middle;
}
.box img {
vertical-align: middle;
}
五. display: table-cell
实现垂直居中
display: table-cell
会使 块级元素『脱离块级属性』,例如宽度不足时会自动收缩

.box {
display: table-cell;
vertical-align: middle;
text-align: center;
}
水平居中
1️⃣ 块级元素水平居中
块级元素, 设置『❗️固定宽度』(
如不设置width,块级元素充满容器。
),在自身添加『左右margin等于auto』
width: 80%;
margin: 0 auto;
2️⃣ 行内元素水平居中
❗️父元素(块级)使用
text-align: center;
,能让内部的匿名行盒(文字)、行内元素(span)、inline-block
元素在父亲里水平居中
text-align: center; 文字在容器中水平居中

版权声明:本文为博主原创文章,未经博主许可不得转载
网友评论