vertical-align: middle doesn't work

The css property vertical-align: middle does not work in this example.

HTML:

<div> <span class='twoline'>Two line text</span> <span class='float'> Float right </span> </div> 

CSS:

.float { float: right; } .twoline { width: 50px; display: inline-block; } div { border: solid 1px blue; vertical-align: middle; } 

The span that is floating on the right is not vertically centered with respect to its containing div. How can I have it vertically centered?

The above code is in this fiddle.

0

4 Answers

You must wrap your element in a table-cell, within a table using display.

Like this:

<div> <span class='twoline'>Two line text</span> <span class='float'>Float right</span> </div> 

and

.float { display: table-cell; vertical-align: middle; text-align: right; } .twoline { width: 50px; display: table-cell; } div { display: table; border: solid 1px blue; width: 500px; height: 100px; } 

Shown here:

6

Vertical align doesn't quite work the way you want it to. See:

This isn't pretty, but it WILL do what you want: Vertical align behaves as expected only when used in a table cell.

There are other alternatives: You can declare things as tables or table cells within CSS to make them behave as desired, for example. Margins and positioning can sometimes be played with to get the same effect. None of the solutions are terrible pretty, though.

2

You should set a fixed value to your span's line-height property:

.float, .twoline { line-height: 100px; } 
1

The answer given by Matt K works perfectly fine.

However it is important to note one thing - If the div you are applying it to has absolute positioning, it wont work. For it to work, do this -

<div> <div> <!-- here position MUST be relative, this div acts as a wrapper--> ... </div> </div> 
0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like