简体   繁体   English

垂直对齐img和li中的文本

[英]vertical align img and text within li

I am trying to vertically align to the middle both an image and some text within a list element but having no luck. 我试图垂直对齐中间的图像和列表元素中的一些文本,但没有运气。

eg: 例如:

<ul>
 <li><img src="somepath" /> sometext
  </li>
<li><img src="somepath2" /> sometext2
  </li>
</ul>

how can i do it? 我该怎么做? thanks 谢谢

Assuming your list items have a fixed height, you can use line-height combined with vertical-align: middle to do this. 假设您的列表项具有固定的高度,您可以使用line-heightvertical-align: middle结合使用。

Example: 例:

ul li {
    display: block;
    height: 100px;
    line-height: 100px;
}

ul li img {
    vertical-align: middle;
}

Working example here. 这里的工作示例。

You should be able to use the CSS property "vertical-align" for the img tag. 您应该能够为img标记使用CSS属性“vertical-align”。 Example: 例:

<style type="text/css">
  img { vertical-align: middle; }
</style>
<ul>
  <li><img src="test.jpg" />test</li>
</ul>

You should wrap text within "li" 你应该在“li”中包装文本

<li><div><span>My text</span></div></li>

li div{
    display: table;
    height: 100%;
    width: 100%;
}
li span{
    display: table-cell;
    vertical-align: middle;
}

Following on from the above answers that suggest the line-height method for vertical centering. 继上述答案后,提出了垂直居中的线高法。 If you apply a font that has glyphs that aren't vertically centered in the font file then the result will be that your element won't be vertically centered either, but be positioned higher or lower than it should be. 如果您应用的字体在字体文件中没有垂直居中的字形,那么结果将是您的元素也不会垂直居中,而是位于比它应该更高或更低的位置。

I had this issue and was tricky to work out. 我遇到了这个问题并且很难解决问题。 If your element doesn't vertically align correctly and you can't work out why, try applying a standard font such as 'Arial'. 如果您的元素没有正确垂直对齐而您无法解决原因,请尝试应用标准字体,例如“Arial”。

See here for more information. 浏览此处获取更多信息。

If you know the height of the image (assuming it is an icon), you can set the line height to the height of the image. 如果您知道图像的高度(假设它是图标),则可以将线高设置为图像的高度。 Then it should work by setting vertical-align:middle . 然后它应该通过设置vertical-align:middle See a live example at w3schools: http://www.w3schools.com/Css/tryit.asp?filename=trycss_vertical-align 请参阅w3schools的实例: http//www.w3schools.com/Css/tryit.asp? filename = trycss_vertical-align

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM