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
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 theline-heightproperty.line-heightalone 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:
Notice the added
<span>.The trick is that the span will be a line with a
40pxline-height (inherited from therolloverdiv). And it will have the float property as well. Because with a floated element, you can’t usevertical-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:
Note that I changed the display of a from
blocktoinline-block, otherwise, novertical-align.And a little fiddle to show it: http://jsfiddle.net/r5RFx/ (I added some borders to see the blocks on the page)