English 中文(简体)
How to vertically center a child element of arbitrary size inside a floated parent element (of known size)?
原标题:

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.)

最佳回答

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!

问题回答

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

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.





相关问题
CSS working only in Firefox

I am trying to create a search text-field like on the Apple website. The HTML looks like this: <div class="frm-search"> <div> <input class="btn" type="image" src="http://www....

jquery ui dialog opens only once

I have a button that opens a dialog when clicked. The dialog displays a div that was hidden After I close the dialog by clicking the X icon, the dialog can t be opened again.

Drop down background url in Safari Issue

selectBox.selectCSS { background: url(/Images/replacementSelectBackground.png) top left no-repeat height:auto; } I have an issue in Safari only where the image is not rendering on top ...

CSS specific for Safari

How do you target specifically safari in css with styles?

Aligning textarea in a form

Ive used the following css code to align my form elements: form { position:relative; } form input { position:absolute; left:11em; } However, the textarea element is not aligned correctly with the ...

Firefox background image horizontal centering oddity

I am building some basic HTML code for a CMS. One of the page-related options in the CMS is "background image" and "stretch page width / height to background image width / height." so that with large ...

CSS problem with page footer

I have defined my page footer in the css file as: #footer { position: absolute; height: 50px; text-align: center; background: #66CCCC; bottom: 0px; left: 0px; width: 100%; height: ...

热门标签