参考链接
CSS居中
行内元素
HTML
<div class="parent">
<span class="child">child</span>
</div>
CSS
.parent {
/*垂直居中 height = line height*/
height: 200px;
line-height: 200px;
/*水平居中*/
text-align: center;
}
.child {
width: 100px;
border: 1px solid blue;
}
或
.parent {
/*垂直居中*/
display: table-cell;
vertical-align: middle;
}
块级元素
HTML
<div class="parent">
<div class="child">child</div>
</div>
CSS
.parent {
height: 500px;
width: 500px;
border: 1px solid orangered;
}
.child {
width: 80px;
height: 80px;
background: lightskyblue;
}
绝对定位 0 + margin: auto;
.parent {
position: relative;
}
.child {
position: absolute;
/*水平居中*/
left: 0;
right: 0;
/*垂直居中*/
top: 0;
bottom: 0;
margin: auto;
}
绝对定位 50% + margin-top/calc(需要提前知道尺寸)
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%;
top: 50%;
margin-top: -40px;
margin-left: -40px;
/*left: calc(50% - 40px);*/
/*top: calc(50% - 40px);*/
}
绝对定位 50% + transform 50%
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
display: table-cell + vertical-align: middle;
.parent {
display: table-cell; /*表现为单元格 行内块*/
vertical-align: middle;
}
.parent {
display: table;
}
.child {
display: table-cell;
vertical-align: middle;
}
伪元素 + inline-block + vertical-align: middle;
.child{
display: inline-block; /*行内块*/
vertical-align: middle;
}
.parent::before{ /*after也可*/
content:'';
height: 100%;
margin: 0;
display: inline-block; /*行内块*/
vertical-align: middle;
}
HTML
<div class="parent"><div class="child">child</div></div>
<div class="parent">
<div class="child">child</div>
</div>
行内元素换行产生空格。
background-clip + padding
background-clip
设置元素的背景(背景图片或颜色)是否延伸到边框、内边距盒子、内容盒子下面。
.parent {
position: relative;
}
.child {
padding: calc((100% - 80px) / 2);
background-clip: content-box;
}
flex
.parent {
display: flex;
align-items: center;
}
grid
例一
.parent {
display: grid;
}
.child {
align-self: center;
}
.parent {
display: grid;
align-items: center;
}
.parent {
display: grid;
align-content: center;
}
例二
HTML
<div class='content'></div>
CSS
html, body{
height: 100%;
margin: 0;
padding: 0;
}
body {
display: grid;
/*未设置行高和列高 默认以整个body为一个项目 即容器大小与项目大小相同*/
/*未设置行高和列高 整个内容区域收缩为.content 且在容器中居中*/
align-content: center;
justify-content: center;
/*所有项目内部居中*/
align-items: center;
justify-items: center;
}
.content {
/*该项目内部居中(佳)*/
justify-self: center;
align-self: center;
width: 300px;
height: 300px;
background: orange;
}