user850010
user850010

Reputation: 6359

How to vertical align tag in a div

I have this HTML code:

<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>

and using this 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;
}

What I'm trying to do is to vertical align h2 tag. This tag will contain a post title, so sometimes it will be single line, sometimes multiline. Also that <div class="news_content"> is just my attempt to make it work. If there is a solution without this div, I can easily remove it.

Here is jsFiddle link to the code above.

Upvotes: 2

Views: 29121

Answers (1)

Passerby
Passerby

Reputation: 10070

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 */
}

Upvotes: 7

Related Questions