Html 如何在列表中垂直对齐多行文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7717378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can you vertically align multi-line text within a list?
提问by Brandon Minton
Example: jsfiddle.net/h5sE6/
css:
css:
ul {
float: left;
margin-right:20px;
}
ul li {
height: 3em;
border: 1px solid #ff0000;
width:200px;
}
html:
html:
<ul>
<li> Some text</li>
<li>Some text<br />some more text</li>
<li>some test text3</li>
<li>even more text<br />and more</li>
</ul>
<ul>
<li> Some text</li>
<li>Some text<br />some more text</li>
<li>some test text</li>
<li>even more text<br />and more</li>
</ul>
This is trivial with vertically aligning text and making the height equal to the line-height if you have one line only but any more than that, things look really screwy.
这对于垂直对齐文本并使高度等于行高来说是微不足道的,如果你只有一行但不止一行,事情看起来真的很糟糕。
回答by Pat
You can do it with a helper :before
element and by adding a nested <span>
:
您可以使用辅助:before
元素并通过添加嵌套来实现<span>
:
ul li span {
display: inline-block;
vertical-align: middle;
}
ul li:before{
content: '';
display: inline-block;
vertical-align: middle;
height: 100%;
}
Here's a demoof it in action.
这是它的实际演示。
This works because two inline-block elements will vertically align with each other. The :before
rule creates an inline-block element that is the same height as its parent, which the variable height <span>
can vertically align with.
这是有效的,因为两个行内块元素将彼此垂直对齐。该:before
规则创建一个与其父元素高度相同的行内块元素,可变高度<span>
可以与其垂直对齐。
For a complete explanation of how it works, see this answerabout vertically aligning images.
回答by Jason Gennaro
You can do this by adding a span
to your markup and then using display:table
etc in your css:
您可以通过将 a 添加span
到您的标记然后display:table
在您的 css 中使用etc来做到这一点:
<ul>
<li><span>Some text</span></li>
<li><span>Some text<br />some more text</span></li>
<li><span>some test text</span></li>
<li><span>even more text<br />and more</span></li>
</ul>
CSS
CSS
ul {
display: table;
border-collapse: collapse;
width: 100%;
}
ul li {
height: 3em;
border: 1px solid #ff0000;
display: table-row;
}
ul li span{
display:table-cell;
vertical-align: middle;
}