2

我有这个 HTML 代码:

<div class="news_item">    
    <div class="featured_leftpart">
        <img src="" width="48" height="48" />
    </div>
    <div class="featured_rightpart">
        <div class="news_content">
            <h2 class="entry-title"><a href="" >TEXT </a></h2>
        </div>
    </div>
</div>

并使用这个 CSS:

.news_item
{
    width:300px;
    position:relative;
    padding:10px;
    height:100px;
    margin:10px;
    border:1px solid #e8e8e8;
}

div.featured_leftpart
{
    position:relative;
    float:left;
    width:64px;
    height:100%;
}

div.featured_leftpart img{
    position:absolute;
    background-color:#ff00ff;
    top:0;
    bottom:0;
    left:0;
    right:0;
    margin:auto;
}

div.featured_rightpart
{
    background-color:#ff0000;    
    float:left;
    width:180px;
    padding-left:10px;
    height:100%;
}

.news_content
{
    background-color:#00ff00;
    position:relative;
}

.news_content h2
{
    vertical-align:middle;
}

我想要做的是垂直对齐 h2 标签。这个标签将包含一个帖子标题,所以有时它是单行的,有时是多行的。这<div class="news_content">也只是我试图让它发挥作用。如果有没有这个的解决方案div,我可以很容易地删除它。

这是上面代码的jsFiddle链接。

4

1 回答 1

7

Extending from comment:

No need to add an extra .news_content, just tell browser how high is a line and vertical-align will work:

http://jsfiddle.net/cJaSL/17/

<div class="featured_rightpart">
    <h2 class="entry-title"><a href="" >TEXT </a></h2>
</div>
div.featured_rightpart
{
    line-height:100px; /* calculated from .news_item */
}
.featured_rightpart h2
{
    vertical-align:middle;
    margin-top:0px; /* need this to clear the default margin */
    margin-bottom:0px;
}

Beware, though, that this solution only works if there's only one line in title.

Edit:

In case multiline is not avoidable, the wrapper seems not avoidable too:

http://jsfiddle.net/cJaSL/18/

<div class="featured_rightpart">
    <div class="title_wrapper">
        <h2 class="entry-title"><a href="" >TEXT<br />multi<br />line </a></h2>
    </div>
</div>
div.title_wrapper {
    display:inline-block;
    vertical-align:middle;
    line-height:1.25em; /* can adjust to look nice */
}
于 2013-05-03T10:52:09.833 回答