The code below (also available as a demo on JS Fiddle) does not position the text in the middle, as I ideally would like it to. I cannot find any way to vertically centre text in a div
, even using the margin-top
attribute. How can I do this?
<div id="column-content">
<img src="http://i.stack.imgur.com/12qzO.png">
<strong>1234</strong>
yet another text content that should be centered vertically
</div>
#column-content {
display: inline-block;
border: 1px solid red;
position:relative;
}
#column-content strong {
color: #592102;
font-size: 18px;
}
img {
margin-top:-7px;
vertical-align: middle;
}
Andres Ilich has it right. Just in case someone misses his comment...
A.) If you only have one line of text:
B.) If you have multiple lines of text:
To make Omar's (or Mahendra's) solution even more universal, the block of code relative to Firefox should be replaced by the following:
The problem with Omar's code, otherwise operative, arises when you want to center the box in the screen or in its immediate ancestor. This centering is done either by setting its position to
position: relative;
orposition:static;
(not with position:absolute nor fixed).And then margin: auto; or margin-right: auto; margin-left: auto;
Under this box center aligning environment, Omar's suggestion does not work. It doesn't work either in Internet Explorer 8 (yet 7.7% market share). So for Internet Explorer 8 (and other browsers), a workaround as seen in other above solutions should be considered.
Update April 10, 2016
Flexboxes should now be used to vertically (or even horizontally) align items.
A good guide to flexbox can be read on CSS Tricks. Thanks Ben (from comments) for pointing it out. I didn't have time to update.
A good guy named Mahendra posted a very working solution here.
The following class should make the element horizontally and vertically centered to its parent.
Add a vertical align to the CSS content
#column-content strong
too:Also see your updated example.
=== UPDATE ===
With a span around the other text and another vertical align:
HTML:
CSS:
Also see the next example.
Try this:
HTML
CSS
The accepted answer doesn't work for multi-line text.
I updated the JSfiddle to show CSS multiline text vertical align as explained here:
It also works with
<br />
in "yet another..."