时间:2021-07-01 10:21:17 帮助过:57人阅读

单行的行内元素
只需要设置单行行内元素的"行高等于盒子的高"即可;
<style>
#father {
width: 500px;
height: 300px;
background-color: skyblue;
}
#son {
background-color: green;
height: 300px;
}
</style>
<div id="father">
<span id="son">我是单行的行内元素</span>
</div>效果:

多行的行内元素
使用给父元素设置display:table-cell;和vertical-align: middle;即可;
<style>
#father {
width: 500px;
height: 300px;
background-color: skyblue;
display: table-cell;
vertical-align:middle;
}
#son {
background-color: green;
}
</style>
<div id="father"><span id="son">我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素</span>
</div>
效果:

块级元素
方案一:使用定位
首先设置父元素为相对定位,再设置子元素为绝对定位,设置子元素的top: 50%,即让子元素的左上角垂直居中;
定高度:设置绝对子元素的 margin-top: -元素高度的一半px; 或者设置transform: translateY(-50%);
<style>
#father {
width: 500px;
height: 300px;
background-color: skyblue;
position: relative;
}
#son {
height: 100px;
background-color: green;
position: absolute;
top: 50%;
margin-top: -50px;
}
</style>
<div id="father">
<div id="son">我是块级元素</div>
</div>不定高度:利用css3新增属性transform: translateY(-50%);
<style>
#father {
width: 500px;
height: 300px;
background-color: skyblue;
position: relative;
}
#son {
width: 100px;
background-color: green;
position: absolute;
left: 50%;
transform: translateY(-50%);
}
</style>
<div id="father">
<div id="son">我是块级元素</div>
</div>效果:

方案二:使用flexbox布局实现(高度定不定都可以)
使用flexbox布局,只需要给待处理的块状元素的父元素添加属性 display: flex; align-items: center;
<style>
#father {
width: 500px;
height: 300px;
background-color: skyblue;
display: flex;
align-items: center;
}
#son {
width: 100px;
height: 100px;
background-color: green;
}
</style>
<div id="father">
<div id="son">我是块级元素</div>
</div>效果:

相关教程:CSS视频教程
以上就是css里上下居中怎么弄?的详细内容,更多请关注Gxl网其它相关文章!