垂直居中
对于单行文本
height和line-height设置相同高度
.p {
height: 20px;
line-height: 20px
}
不定高
.father {
positon: relative;
}
.son {
position: absolute;
top: 50%;
transform: transiate(0, -50%);
}
.father {
positon: relative;
}
.son {
position: absolute;
top: 0;
bottom: 0;
marigin: auto;
}
flex布局 + align-items: center;
水平居中
对于给定宽度,可以简单使用margin: 0 auto;
.center {
width: 960px;
margin: 0 auto;
}
或者在父元素中添加text-align:center;子元素添加display: inline-block;
.father {
width: 300ox;
text-align: center;
}
.son{
display: inline-block;
}
更多方法浏览https://www.w3cplus.com/css/elements-horizontally-center-with-css.html
垂直水平居中
HTML:
<div class="set">
<div class="con"></div>
<div>
需要知道元素的宽高
.con{
width: 100px;
height: 100px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
.con{
width: 100px;
height: 150px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -75px;
margin-left: -50px;
}
或者把父元素改为display: table-cell
.set{
width: 300px;
height: 300px;
display: table-cell;
vertical-align: middle;
text-align: center;
}
或者使用flex布局
.set{
width: 300px;
height: 300px;
display: flex;
justify-content: center;
align-items: center;
}
or
#box {
position: absolute;
width: 100px;
height: 100px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}