如何在 span 标签中对某个内容进行垂直对齐?

如何使跨度中间的“ x”垂直对齐?

.foo {
height: 50px;
border: solid black 1px;
display: inline-block;
vertical-align: middle;
}


<span class="foo">
x
</span>
321721 次浏览

遗憾的是,竖直对齐的 css 属性没有完成您所期望的工作。这篇文章解释了使用 css 对元素进行垂直对齐的两种方法。

使用 line-height:50px;代替高度,这样应该可以达到目的;)

将 paddingtop 设置为一个合适的值,将 x 向下推,然后从高度中减去 paddingtop 的值。

这对我有用(Keltex 也是这么说的)

.foo {
height: 50px;
...
}
.foo span{
vertical-align: middle;
}


<span class="foo"> <span>middle!</span></span>

请注意,如果在 span中有一个很长的句子,因为没有足够的空间而中断了行,那么 line-height方法就会失败。在这种情况下,您将有两行,其间隙为属性中指定的 N 个像素的高度。

当我想要显示一个右边有垂直居中的文本的图像时,我坚持使用它,这在一个响应式的 web 应用程序中是可行的。作为一个基础,我使用的方法建议由埃里克尼克斯和菲利普 Tadeo。

如果你想达到以下目标:

desktop

还有这个:

mobile

.container {
background: url( "https://i.imgur.com/tAlPtC4.jpg" ) no-repeat;
display: inline-block;
background-size: 40px 40px; /* image's size */
height: 40px; /* image's height */
padding-left: 50px; /* image's width plus 10 px (margin between text and image) */
}


.container span {
height: 40px; /* image's height */
display: table-cell;
vertical-align: middle;
}
<span class="container">
<span>This is a centered sentence next to an image</span>
</span>

如果需要多行,这是最简单的方法。用另一个 span包装您的 span文本,并用 line-height指定其高度。多线路的诀窍是重置内部 spanline-height

<span class="textvalignmiddle"><span>YOUR TEXT HERE</span></span>
.textvalignmiddle {
line-height: /*set height*/;
}


.textvalignmiddle > span {
display: inline-block;
vertical-align: middle;
line-height: 1em; /*set line height back to normal*/
}

演示

当然外围的 span可能是 div或者别的什么

我需要这个链接,所以我用一个 a-tag 和一个 div 包装了 span,然后将 span 标记本身居中

超文本标示语言

<div>
<a class="tester" href="#">
<span>Home</span>
</a>
</div>

CSS

.tester{
display: inline-block;
width: 9em;
height: 3em;
text-align: center;
}
.tester>span{
position: relative;
top: 25%;
}

CSS 垂直中心图像和文本

我有一个垂直图像中心和文本创建一个演示,我也有火狐,chrome,Safari,Internet Explorer 9和8的测试。

它是非常简短和容易的 css 和 html,请检查下面的代码,你可以找到屏幕短的输出。

超文本标示语言

<div class="frame">
<img src="capabilities_icon1.png" alt="" />
</div>

CSS

  .frame {
height: 160px;
width: 160px;
border: 1px solid red;
white-space: nowrap;
text-align: center; margin: 1em 0;
}


.frame::before {
display: inline-block;
height: 100%;
vertical-align: middle;
content:"";
}


img {
background: #3A6F9A;
vertical-align: middle;
}

输出 在此输入图像描述

弹性方式:

.foo {
display: flex;
align-items: center;
justify-content: center;
height: 50px;
}

只是提供一个替代方案,以防您将元素封装在一个灵活的容器中(例如: display: flex) :

align-self: center;

更多信息