views:

192

answers:

3

Well, the title says it all. How to vertically center a child element of arbitrary size inside a floated parent element (of known size)?

display: table-cell; vertical-align: middle; no longer seems to work when the element is floated.

I created an SSCCE here: http://mathiasbynens.be/demo/center-vertically-inside-float

Without float, everything works as it should. But as soon as the parent element is floated, the vertical alignment fails.

Any ideas how to work around this?

Edit: I should’ve added that the child elements are supposed to be images. In my example page I’m using paragraphs, since I assumed I could apply whatever CSS those p elements needed to img elements with display: block; as well. (Fail.)

+1  A: 

Float disables table-cell, because cells can’t be floated. So basically I would recommend the standard stuff – using floated shim technique or absolute positioning.

riddle
The problem is that absolute positioning cannot be used on the child element, since its size varies.
Mathias Bynens
+2  A: 

If it's one-liner, then set line-height of p to height of the container.

porneL
Your answer works for paragraphs (block level elements), which is what I asked for :) Thanks!Ok, so I guess my SSCCE was a bit *too* simple to demonstrate my real problem. The child element is not supposed to be a paragraph, but an image (of arbitrary height), which requires some additional CSS.
Mathias Bynens
+1  A: 

Ok, so thanks to porneL’s answer, I found the solution to my problem.

In my SSCCE I used paragraphs as child elements (and porneL gave the correct answer as far as that goes), but what I really needed were images. Turns out this needs a little bit of additional CSS:

div { width: 780px; height: 200px; vertical-align: middle; text-align: center; float: left; }
 div img { vertical-align: middle; }

Thanks for the help, guys!

Mathias Bynens
You can remove `display: table-cell;` from there. `float` forces block display (same as `position:absolute`) — http://www.w3.org/TR/CSS21/visuren.html#dis-pos-flo
porneL
Thanks, edited.
Mathias Bynens