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.
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.
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.
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.
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With