结构:
<div class="parent" style="margin: 10px;">
<div class="child">块元素水平垂直居中</div>
</div>
<div class="parent" style="margin: 10px;">
<span class="child">行内元素水平垂直居中</span>
</div>
<div class="parent" style="margin: 10px;">
<span class="child" style="display: inline-block;">行内块元素水平垂直居中</span>
</div>
布局:
第一种:flex布局
核心:
父元素:
display: flex;
align-items: center;
justify-content: center;
<style>
* {
margin: 0;
padding: 0;
}
.parent {
width: 500px;
height: 500px;
background-color: #bfa;
display: flex;
align-items: center;
justify-content: center;
}
.child {
background-color: red;
width: 150px;
height: 150px;
}
</style>
第二种:position定位
核心:
父元素:绝对定位
子元素:相对定位,会将元素都转为行内块
调整子元素的位置的方法:
- 子元素left:50%;top:50%,
- 无需宽高transform:translate(-50%,-50%)
- 需要宽高,margin-left/margin-top子元素宽高的一半
- 子元素left:0;top:0;right:0;bottom:0
- 需要宽高,margin:0,auto;
<style>
* {
margin: 0;
padding: 0;
}
.parent {
width: 500px;
height: 500px;
background-color: #bfa;
position: relative;
}
.child {
background-color: red;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
</style>
<style>
* {
margin: 0;
padding: 0;
}
.parent {
width: 500px;
height: 500px;
background-color: #bfa;
position: relative;
}
.child {
background-color: red;
position: absolute;
width: 150px;
height: 150px;
left: 50%;
top: 50%;
margin-left: -75px;
margin-top: -75px;
}
</style>
<style>
* {
margin: 0;
padding: 0;
}
.parent {
width: 500px;
height: 500px;
background-color: #bfa;
position: relative;
}
.child {
background-color: red;
position: absolute;
width: 150px;
height: 150px;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
</style>
第三种:grid布局
核心:
父元素:
display:grid;
place-item:center;
<style>
* {
margin: 0;
padding: 0;
}
.parent {
width: 500px;
height: 500px;
background-color: #bfa;
display: grid;
place-items: center;
}
.child {
background-color: red;
}
</style>
第四种:table布局
核心:
父元素:
display:table-cell;
vertical-align: middle;
针对子元素为行内元素/行内块元素:
父元素:text-align:center
针对子元素为块元素:
子元素:margin:0 auto;
<style>
* {
margin: 0;
padding: 0;
}
.parent {
width: 500px;
height: 500px;
background-color: #bfa;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.child {
background-color: red;
width: 150px;
height: 150px;
margin: 0 auto;
}
</style>
第五种:只针对行内元素(不包含行内块元素)
核心:
父元素:
text-align:center
子元素:
line-height:为父元素的高
<style>
* {
margin: 0;
padding: 0;
}
.parent {
width: 500px;
height: 500px;
background-color: #bfa;
text-align: center;
}
.child {
background-color: red;
width: 150px;
height: 150px;
line-height: 500px;
}
</style>