CSS 垂直居中单行和多行 li 文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4095165/
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
Center single- AND multi-line li text vertically
提问by Raphael Müller
I have an unordered list with a background-image set. All list-items have the same height, the background-image is positioned left center.
我有一个带有背景图像集的无序列表。所有列表项具有相同的高度,背景图像位于左中心。
The text of each item should be centered verticallyto the li. This works well with single-line text (by setting the line-height according to the height of the li), but not with two lines of text.
每个项目的文本应与 li垂直居中。这适用于单行文本(通过根据 li 的高度设置 line-height),但不适用于两行 text。
I could add "line-height:normal" to the two-line item, but I want a solution that works for all items.
我可以在两行项目中添加“line-height:normal”,但我想要一个适用于所有项目的解决方案。
How can I do this?
我怎样才能做到这一点?
Example:
例子:
li {
list-style-type:none;
padding-left:40px;
height:36px;
line-height:36px;
background:url('tick.png') no-repeat 0 50%;
}
回答by
this is a most crossbrowser solution
这是一个最跨浏览器的解决方案
li {
width : 200px;
line-height : 100px;
height : 100px;
border : 1px blue solid;
}
li span {
display : -moz-inline-box; /* FF2 or lower */
display : inline-block; /* FF3, Opera, Safari */
line-height : normal;
vertical-align : middle;
}
li span { *display : inline;} /* haslayout for IE6/7 */
<ul>
<li><span>My text</span></li>
<li><span>My longer text</span></li>
<li><span>My text, but this time is really wide</span></li>
<li><span>My text, some thoughts about how much it will expand in this item.</span></li>
</ul>
I used star hack for brevity, you should avoid. Just use html5boilerplate solution, it uses conditional comments on body tag
为简洁起见,我使用了 star hack,你应该避免。只需使用 html5boilerplate 解决方案,它在 body 标签上使用条件注释
回答by MatTheCat
li {
height:200px;
line-height:200px;
border:1px solid red;
}
li span {
vertical-align:middle;
display:inline-block;
line-height:1.2;
}
<li>
<span>two<br />lines</span>
</li>
It should work.
它应该工作。
EDIT : updated to see changes
编辑:更新以查看更改