方式一:line-height 使文本居中
HTML
<div c lass="container">
<div class="box"></div>
</div>
CSS
.box{
width: 150px;
height: 100px;
line-height: 100px;
background-color: red;
}
方式二:line-height 使盒子居中(局限)
- 子元素必须有文本
- 子元素必须为行内级元素
- 父元素和子元素的字体大小必须相同
HTML
<div c lass="container">
<div class="box">xxx</div>
</div>
CSS
.container{
width: 500px;
height: 300px;
background: #ddd;
line-height: 300px;
}
.box{
display: inline-block;
width: 150px;
height: 100px;
background-color: red;
line-height: 100px;
}
方式三:绝对定位 + transform:translate
HTML
<div class="container">
<div class="box"></div>
</div>
CSS
.container{
width: 500px;
height: 300px;
background: #ddd;
position: relative;
}
.box{
width: 150px;
height: 100px;
background: red;
position: absolute;
top: 50%;
transform: translate(0, -50%);
}
方式四:绝对定位 + margin
HTML
<div class="container">
<div class="box"></div>
</div>
CSS
.container{
width: 500px;
height: 300px;
background: #ddd;
position: relative;
}
.box{
width: 150px;
height: 100px;
background: red;
position: absolute;
top:0;
bottom: 0;
margin: auto 0;
}
方式五:flex布局
HTML
<div c lass="container">
<div class="box"></div>
</div>
CSS
.container{
display: flex;
align-items: center;
width: 500px;
height: 300px;
background: #ddd;
}
.box{
display: inline-block;
width: 150px;
height: 100px;
background-color: red;
}