【发布时间】:2010-10-18 10:55:27
【问题描述】:
如何让“x”在跨度中间垂直对齐?
.foo {
height: 50px;
border: solid black 1px;
display: inline-block;
vertical-align: middle;
}
<span class="foo">
x
</span>
【问题讨论】:
如何让“x”在跨度中间垂直对齐?
.foo {
height: 50px;
border: solid black 1px;
display: inline-block;
vertical-align: middle;
}
<span class="foo">
x
</span>
【问题讨论】:
【讨论】:
弹性盒方式:
.foo {
display: flex;
align-items: center;
justify-content: center;
height: 50px;
}
【讨论】:
.foo 是一个跨度display: flex-inline 会更合适
如果您需要多行,这是最简单的方法。将 span'd 文本包裹在另一个 span 中,并使用 line-height 指定其高度。多行的诀窍是重置内部span 的line-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 或whathaveyou
【讨论】:
spans,与任何其他内联元素一样,can contain any HTML inline element。无论如何,如果有必要,我写道textvalignmiddle 可以是div(如果您不喜欢使用spans,可以将其设置为display:inline;)
span 是 html 的 generic inline container,并没有暗示只是文本; ` 它可用于对 元素 进行分组以进行样式设置...`。我建议在将您的个人编码标准推向其他人声明它们为事实之前阅读规范
请注意,如果您在 span 中有一个长句,由于空间不足而导致换行,则 line-height 方法会失败。在这种情况下,您将有两条线与属性中指定的 N 个像素的高度有间隙。
当我想在右侧显示具有垂直居中文本的图像时,我坚持使用它,这适用于响应式 Web 应用程序。作为基础,我使用 Eric Nickus 和 Felipe Tadeo 建议的方法。
如果你想达到:
还有这个:
.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>
【讨论】:
CSS 垂直居中图片和文字
我已经为垂直图像中心和文本创建了一个演示,我也在 firefox、chrome、safari、internet explorer 9 和 8 上进行了测试。
非常简单的css和html,请检查下面的代码,你可以在screenshort上找到输出。
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;
}
【讨论】:
我需要这个链接,所以我用一个 a-tag 和一个 div 包裹了 span,然后将 span 标签本身居中
HTML
<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%;
}
【讨论】:
这对我有用(Keltex 也这么说)
.foo {
height: 50px;
...
}
.foo span{
vertical-align: middle;
}
<span class="foo"> <span>middle!</span></span>
【讨论】:
将 padding-top 设置为适当的值以将 x 向下推,然后从高度中减去 padding-top 的值。
【讨论】:
使用line-height:50px; 代替高度。这应该可以解决问题;)
【讨论】:
很遗憾,vertical-align css 属性并没有达到您的预期。 This article 解释了两种使用 css 垂直对齐元素的方法。
【讨论】: