pindol
pindol

Reputation: 2110

vertical text align in relative div

I have a div with position:relative; contained in a div with fixed width. Inside it (div with position relative) there is some text. The problem is that I need to center it in vertical and in some cases the text is composed by one line and in others by two. My css code is this:

.rollover{
position: relative;
width: auto;
background-color: #000;
opacity: 0.5;
height: 40px;
overflow: hidden;
padding-left: 10px;
}

.rollover a{
font-family: lucida;
font-size: 10px;
color: #FFF;
display: block;
line-height: 11px;
float: left;
text-decoration: none;
}

and my html code is:

<div class="rollover">
    <a href="">ONE LINE TEXT</a>
</div>

or

<div class="rollover">
    <a href="">FIRST LINE<br/>SECOND LINE</a>
</div>

How can I do?

Thanks, Mattia

Upvotes: 1

Views: 3021

Answers (1)

Py.
Py.

Reputation: 3599

Having recently faced the problem, the solution I came up with (if you have to do it in a case where you can't use display:table-cell) is to add a little markup and to use the line-height property.

line-height alone on the outer div works fine when there is only one line. When you face something that could be multi line, the solution is to use two line height.

The markup used is the following:

<div class="rollover">
    <span>
         <a href="">ONE LINE TEXT</a>
    </span>
</div>
<div class="rollover">
    <span>
         <a href="">FIRST LINE<br/>SECOND LINE</a>
    </span>
</div>​

Notice the added <span>.

The trick is that the span will be a line with a 40px line-height (inherited from the rollover div). And it will have the float property as well. Because with a floated element, you can't use vertical-align. Inside that span, we'll have our link with a line height of 11px and a vertical align-middle. That is the middle of the span. And there it is.

The css needed is the following:

.rollover{
    position: relative;
    width: auto;
    background-color: #000;
    opacity: 0.5;
    height: 40px;
    overflow: hidden;
    padding-left: 10px;
    line-height:40px;
}

.rollover span{
    float: left;
}
.rollover a{
    font-family: lucida;
    font-size: 10px;
    color: #FFF;
    line-height: 11px;
    text-decoration: none;
    vertical-align:middle;
    display:inline-block;    
}

Note that I changed the display of a from block to inline-block, otherwise, no vertical-align.

And a little fiddle to show it: http://jsfiddle.net/r5RFx/ (I added some borders to see the blocks on the page)

Upvotes: 4

Related Questions