在 div 中垂直对齐 span

15

http://jsfiddle.net/UmHNL/2/

<div class="container">

    <span>Some text, yay</span>

</div>

<div class="container">

    <span>Some text, yay. But shit time, there is alot of text, so we get a problem with breaking lines and the given height :( How can I align vertical now?</span>

</div>
<style>
.container {
    width: 100%;
    height: 50px;
    line-height: 50px;
    border: 1px solid black;
}

.container span {
    padding-left: 30px;
}
</style>

当屏幕宽度太小时,这种解决方案效果很好,但文本会被分成多行。

我在谷歌中搜索此问题时发现了很多疯狂且过于复杂的解决方案,需要使用JavaScript和DIV来调整我的内容位置。有人能帮我在不添加更多标记的情况下使其生效吗?:)

无需支持Internet Explorer和旧版本浏览器。

谢谢


1
你需要的是这个吗? - Mr. Alien
一个 <span> 嵌套在一个 <div> 里会起作用吗? - aaron-bond
@Mr. Alien,我会看一下它是否可以与其余的标记一起使用。这里是一个简化版本 :) - user89862
@Johannes 当然可以 :) - Mr. Alien
对我来说,这似乎有点“hacky”。但它能够正常工作!所以当你读完这个帖子后,我会将其删除。谢谢朋友! - user89862
2个回答

12

你应该尝试这个:

.container {
    width: 100%;
    height: 50px;
    border: 1px solid black;
    display: table;
    text-align: center;
}

.container span {
    display: table-cell;
    vertical-align: middle;
}

3

更新您的CSS

.container {
  width: 100%;
  height: 50px;
  display: table-cell;
  border: 1px solid black;
  text-align: center;
  vertical-align: middle;
}

.container span {
}

但是为什么你需要在span中添加padding-left: 30px;呢?你已经在.container中居中了文本,并确保在.container中添加了vertical-align: middle;以垂直对齐文本。 - Ishank Gupta
1
那个不起作用,但是说容器是表格,而 span 是表格单元格效果更好 :) - user89862
抱歉,我链接了错误的代码片段,而且我误删了评论,本应该进行编辑的。 :) - user89862
解决方案:http://jsfiddle.net/UmHNL/7/ - user89862
1
@Johannes 我认为这不是解决方案,因为第二个单元格没有遵守50像素的高度。 - Mihai Matei
@Johannes:我认为我们不应该将span的显示更改为“table-cell”,因为当您在.container中添加任何其他标记时,它会破坏布局。现在我认为我们不需要使用vertical-align,因为您正在使用padding添加空白间距。 - Ishank Gupta

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接