Randomblue
Randomblue

Reputation: 116283

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.

Upvotes: 52

Views: 134650

Answers (4)

Afifa Rih
Afifa Rih

Reputation: 191

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

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

Upvotes: 11

Matt K
Matt K

Reputation: 6709

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: http://jsfiddle.net/e8ESb/7/

Upvotes: 49

Akshaya Shanbhogue
Akshaya Shanbhogue

Reputation: 1448

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 style="position:absolute; hei...">
   <div style="position:relative; display: table-cell; vertical-align:middle; hei..."> 
      <!-- here position MUST be relative, this div acts as a wrapper-->
      ...
   </div>
</div>

Upvotes: 3

GlyphGryph
GlyphGryph

Reputation: 4794

Vertical align doesn't quite work the way you want it to. See: http://phrogz.net/css/vertical-align/index.html

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

http://jsfiddle.net/e8ESb/6/

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.

Upvotes: 11

Related Questions