The vertical average for an item inside a variable height container

I have the following situation:

enter image description here

Variable height div (#container) with the image inside (the image that fits inside another div) that I need to float: right and align vertically in the middle. How to do it?

Thanks.

EDIT

Perhaps I did not give a sufficiently clear idea that I do not know in advance how much content the container has, from a few lines to the wall of the text, so any solution based on its height will not work (and that my problem is: P)

This is a script with an example of possible content for which image alignment: http://jsfiddle.net/9DbmN/

+4
source share
2 answers

You should take a look at Centering in the Unknown by Chris Koyer. Imo is a pretty solid solution for the holy grail of vertical centering.

+2
source

I would not be discouraged by the use of tables here))) If you use a table of two cells with vertical-align: middle mounted on its td elements, it will ideally (and easily !!!) solve your problem.

If you want to have two containers, one of which (the one that has the image) will move to the right and need centering - I would say that you do not need to use the float property for this. Because: a) as I understand it, you do not need you to leave the content on the left to be under this image, right? b) floats are block level elements, and you cannot change it even if you set display: table-cell , the browser will still make it like display: block - which will lead me to the conclusion that you will not be able to center it css ( at least by the means of which I know).

If you don't need ie7 support, maybe this is a workaround:

HTML:

 <div id="container"> <div class="content">Content goes here, vertically aligned with the image</div> <div class="i_used_to_be_floated_right">Image goes here</div> </div> 

CSS

 #container { display: table; width: 100%; } .content, .i_used_to_be_floated_right { display: table-cell; vertical-align: middle; } .content { background: green; width: 80%; } .i_used_to_be_floated_right{ background: red; width: 20%; } 

A live live example can be seen here: http://jsfiddle.net/skip405/sDXMj/1/

But if you need ie7 - I would vote for the table solution that I said at the very beginning.

0
source

All Articles