CSS中span元素垂直居中【解决span元素内基线对齐问题】
在样式的书写中,我们常常使用以下方式实现垂直居中,若span元素内例外,解决办法看文章最后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内的元素,并不能垂直居中对齐,查了原因发现是因为默认按照底部基线对齐,问题如左图,正确的应该如右图:
[img=auto,300px]https://gitee.com/Gao-by/blog-park-essay-pictures/raw/master/imgs/20240806102304.png[/img] [img=auto,300px]https://gitee.com/Gao-by/blog-park-essay-pictures/raw/master/imgs/20240806102523.png[/img] **解决办法如下:**
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;
- }
复制代码 来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |