Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vertical-align: middle doesn't work

Tags:

html

css

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.

like image 310
Randomblue Avatar asked Nov 01 '11 13:11

Randomblue


People also ask

Why does Align Center doesn't work?

Short answer: your text isn't centered because the elements are floated, and floated elements "shrink" to the content, even if it's a block level element.

How does vertical-align middle work?

To get them centered along a line, you'd use vertical-align: middle; . Although note that it centers the text according to its tallest ascender and deepest descender. Each element lines up according to the line you've set, which doesn't change from element to element.

How do I center align vertically in HTML?

For vertical alignment, set the parent element's width / height to 100% and add display: table . Then for the child element, change the display to table-cell and add vertical-align: middle . For horizontal centering, you could either add text-align: center to center the text and any other inline children elements.


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

like image 180
Matt K Avatar answered Oct 19 '22 22:10

Matt K


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.

like image 20
GlyphGryph Avatar answered Oct 20 '22 00:10

GlyphGryph