找回密码
 立即注册
首页 业界区 业界 CSS中span元素垂直居中【解决span元素内基线对齐问题】 ...

CSS中span元素垂直居中【解决span元素内基线对齐问题】

嗅叽 3 天前
CSS中span元素垂直居中【解决span元素内基线对齐问题】

在样式的书写中,我们常常使用以下方式实现垂直居中,若span元素内例外,解决办法看文章最后
  1.   text
复制代码
1.flex布局方式垂直居中
  1. .parent{
  2.     display:flex;
  3.     align-items:center
  4. }
复制代码
2.line-height方式垂直居中
  1. .parent{
  2.     height:64px;
  3. }
  4. .child{
  5.         height:64px;
  6.         line-height:64px;
  7. }
复制代码
3.绝对定位方式垂直居中
  1. .parent{
  2.     position:relative;
  3. }
  4. .child{
  5.         positon:absolute;
  6.         top:50%;
  7.         transform:translateY(-50%)
  8. }
复制代码
发现问题:

实际应用中发现,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
  1. .parent {
  2.   line-height: 64px;
  3.   height: 64px;
  4.   background-color: antiquewhite;
  5. }
  6. .child {
  7.   background-color: black;
  8.   line-height: 1;
  9.   vertical-align: text-top;
  10. }
复制代码
2.如果希望父元素parent设置为100%,继承祖父元素的高度
  1. .parent {
  2.   height: 100%;
  3.   line-height: 1;
  4.   background-color: antiquewhite;
  5. }
  6. .child {
  7.   background-color: black;
  8.   vertical-align: text-top;
  9. }
复制代码
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册