CSS中span元素垂直居中【解决span元素内基线对齐问题】
在样式的书写中,我们常常使用以下方式实现垂直居中,若span元素内例外,解决办法看文章最后
<div class="parent">
<span class="child">text</span>
</div>
1.flex布局方式垂直居中
.parent{
display:flex;
align-items:center
}
2.line-height方式垂直居中
.parent{
height:64px;
}
.child{
height:64px;
line-height:64px;
}
3.绝对定位方式垂直居中
.parent{
position:relative;
}
.child{
positon:absolute;
top:50%;
transform:translateY(-50%)
}
发现问题:
实际应用中发现,span内的元素,并不能垂直居中对齐,查了原因发现是因为默认按照底部基线对齐,问题如左图,正确的应该如右图:
**解决办法如下:**
1.如果希望父元素parent设置为固定高度,例如64px
.parent {
line-height: 64px;
height: 64px;
background-color: antiquewhite;
}
.child {
background-color: black;
line-height: 1;
vertical-align: text-top;
}
2.如果希望父元素parent设置为100%,继承祖父元素的高度
.parent {
height: 100%;
line-height: 1;
background-color: antiquewhite;
}
.child {
background-color: black;
vertical-align: text-top;
}
© 版权声明
本站所有资源来自于网络,仅供学习与参考,请勿用于商业用途,否则产生的一切后果将由您(转载者)自己承担!
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
THE END
暂无评论内容