未知宽高元素水平垂直居中的实现方法:
第一种:用flex布局
设置元素的父级为弹性盒子display:flex,设置父级和盒子内部子元素水平垂直都居中justify-content:center; align-items:center ,这种方式代码简洁,但是兼容性ie 11以上支持。
<style>
.container{
background-color: palevioletred;
width: 400px;
height: 400px;
display: flex;
justify-content: center;
align-items: center;
}
.box{
width: 100px;
height: 100px;
background-color: darkkhaki;
}
</style>
<div class="container">
<div class="box"></div>
</div>
第二种:定位+margin:auto
父级设置为相对定位,子级绝对定位 ,并且四个定位属性的值都设置为0(值相等即可)
这时如果子级没有设置宽高,则会被拉开到和父级一样的宽高;
如果这里子元素设置了宽高,所以宽高会按照我们的设置来显示,再给它一个margin:auto它就可以上下左右都居中了。
<style>
.container{
background-color: palevioletred;
position: relative;
width: 400px;
height: 400px;
}
.box{
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
width: 100px;
height: 100px;
background-color: darkkhaki;
}
</style>
<div class="container">
<div class="box"></div>
</div>
第三种:定位+负值 或 定位+transform
- 子绝父相,给父盒子设置相对定位,给子盒子设置绝对定位;
- 给子盒子添加
top
和left
边偏移量,使其向下和向右偏移父盒子的宽|高的50% - 偏移之后还需将子盒子往回走自己宽|高的一半实现居中,平常可以用
margin-top:-50px
,margin-left:-50px;
- 如果遇到更复杂的计算可以用 transform: translate(-50%,-50%)。
<style>
.container{
background-color: palevioletred;
position: relative;
width: 400px;
height: 400px;
}
.box{
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
width: 100px;
height: 100px;
background-color: darkkhaki;
}
</style>
<div class="container">
<div class="box"></div>
</div>
第四种:table布局
- 设置父元素为单元格:display:table-cell;
- 给父盒子样式中添加属性
text-align:center
和vertical-align:middle
即可将子元素水平居中。 - 因为
vertical-align
属性只对行内元素和行内块元素有效,因此,要将子盒子添加display:inline-block
将其转换为为行内块。
<style>
.container{
background-color: palevioletred;
width: 400px;
height: 400px;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.box{
width: 100px;
height: 100px;
background-color: darkkhaki;
display: inline-block;
}
</style>
<div class="container">
<div class="box"></div>
</div>
第五种:grid布局
- 父盒子设置为grid布局:display:grid;
- 给父盒子样式中添加属性
justify-content:center
和align-items:center
即可将子元素水平居中。
注:【grid布局中这两个属性的用法于flex布局中一样】
justify-content
用于设置主轴上子元素的排列方式,设置center
时表示在主轴居中对齐。
align-items
用于设置侧轴上子元素的排列方式,设置center
时表示在侧轴居中对齐。
<style>
.container{
background-color: palevioletred;
width: 400px;
height: 400px;
display: grid;
text-align: center;
vertical-align: middle;
}
.box{
width: 100px;
height: 100px;
background-color: darkkhaki;
}
</style>
<div class="container">
<div class="box"></div>
</div>