当文本不在表格单元格中时,如何垂直对齐文本?

时间:2013-06-20 18:04:28

标签: css

我正在移动网站上工作,我有几个页面显示右侧带有文字的小缩略图:http://sunsetwesterngardencollection.com/mobile/the-collection

缩略图定位良好,但文字受到挑战。我做了一些研究,找到了一个选项,但它似乎没有正常工作。

以下是内容的HTML:

<ul id="plants">

<li class="plant">
<a href="http://sunsetwesterngardencollection.com/mobile/plant/amistad-salvia"><img src="http://sunsetwesterngardencollection.com/photos/thumbnails/salvia_amistad_thumb.jpg" alt="&#8216;Amistad&#8217; Salvia"  />
<span class="plant-name">&#8216;Amistad&#8217; Salvia</span></a>
<div class="orange-slice"></div>
</li>

<li class="plant">
<a href="http://sunsetwesterngardencollection.com/mobile/plant/black-adder-phormium"><img src="http://sunsetwesterngardencollection.com/photos/thumbnails/phormium_black_adder_thumb.jpg" alt="&#8216;Black Adder&#8217; Phormium"  />
<span class="plant-name">&#8216;Black Adder&#8217; Phormium</span></a>
<div class="orange-slice"></div>
</li>

<li class="plant">
<a href="http://sunsetwesterngardencollection.com/mobile/plant/blue-riding-hood-penstemon"><img src="http://sunsetwesterngardencollection.com/photos/thumbnails/penstemon_blue_riding_hood_thumb.jpg" alt="&#8216;Blue Riding Hood&#8217; Penstemon"  />
<span class="plant-name">&#8216;Blue Riding Hood&#8217; Penstemon</span></a>
<div class="orange-slice"></div>
</li>
</ul>

这是CSS:

ul#plants li { 
    width: 100%;
    height: auto;
    position: relative;
 } 

.orange-slice { 
    width: 100%; 
    height: 2px; 
    clear: both;
    background: #e1562e; 
} 

ul#plants li img { float: left; width: 20%; margin: 0; } 

ul#plants li span,
ul#plants li span a:link,
ul#plants li span a:visited { 
    color: #e1562e; 
    font-size: 1.3em; 
    font-weight: 500;
    position: absolute; 
    top: 25%; 
    left: 23%;
    text-transform: uppercase;
    display: table-cell;
    vertical-align: middle;
     }

当文本不在表格单元格中时,垂直对齐文本的正确方法是什么?

谢谢!

2 个答案:

答案 0 :(得分:3)

使line-height与文本所在元素的高度相同。

答案 1 :(得分:1)

你不需要JAVASCRIPT做这个!

因此,在查看您的代码之后,我有一个解决方案以及一些建议。

首先让我们来看看你可以做些什么来解决这个问题: 我们将以下内容添加到您的css中,以使列表项像表格一样。

#plant.plants { display: table;}

然后让我们专注于你的包含锚:

#plant.plants a { display: table-row;}

最后让我们攻击你说文字的范围:

#plant.plants a span { display: table-cell;}

删除您目前在所述范围内的以下规则

//remove
position: absolute;
top: 25%;
left: 23%;

现在看起来有点时髦,但您可以通过更改图像宽度来调整行。现在给我一个建议,我不确定你是否使用'orange-slice'作为交互式下拉。但如果你只是为了造型师的目的而使用我建议只添加:

#plant.plants { border-bottom: 2px solid #e1562e; }