文章目录
使用绝对定位和负外边距对块级元素进行垂直居中
<style>
#box {
width: 300px
;
height: 300px
;
background: #ddd
;
position: relative
;
}
#inner {
width: 150px
;
height: 100px
;
background: orange
;
position: absolute
;
top: 50%
;
margin: -50px 0 0 0
;
}
</style>
<div id=
"box">
<div id=
"inner">
<span>1. 使用绝对定位和负外边距对块级元素进行垂直居中</span>
</div>
</div>
使用绝对定位和transform
<style>
#box {
width: 300px
;
height: 300px
;
background: #ddd
;
position: relative
;
}
#inner {
width: 150px
;
height: 100px
;
background: orange
;
position: absolute
;
top: 50%
;
transform: translate(0, -50%
);
}
</style>
<div id=
"box">
<div id=
"inner">
<span>使用绝对定位和transform</span>
</div>
</div>
绝对定位结合margin: auto
<style>
#box {
width: 300px
;
height: 300px
;
background: #ddd
;
position: relative
;
}
#inner {
top: 0
;
bottom: 0
;
width: 150px
;
height: 100px
;
background: orange
;
position: absolute
;
margin: auto 0
;
}
</style>
<div id=
"box">
<div id=
"inner">
<span>
绝对定位结合margin: auto</span>
</div>
</div>
使用flex布局
<style>
#box {
width: 300px;
height: 300px;
background: #ddd;
display: flex;
align-items: center;
}
#inner {
width: 150px;
height: 100px;
background: orange;
}
</style>
<div id="box">
<div id="inner">
<span>使用flex布局</span>
</div>
</div>
使用flex布局 方式二
<style>
#box {
width: 300px
;
height: 300px
;
background: #ddd
;
display: flex
;
flex-direction: column
;
justify-content: center
;
}
#inner {
width: 150px
;
height: 100px
;
background: orange
;
}
</style>
<div id=
"box">
<div id=
"inner">
<span>使用flex布局 方式二</span>
</div>
</div>