Vertical alignment of an image in a div element?

I have a div element whose height is set using em and whose width is set as a percentage. Inside there is an image. It has a percentage width (83%). However, if I am in resolution when this div element starts to narrow a bit, the image also narrows, but instead of capturing the entire div (as it should), the image just gets small and only appears at the top of the div. To compensate for this, I want to vertically align my image in a div element. How can i do this?

+4
source share
2 answers

vertical-align does not work in DIV elements. the only way to do this is to set this property to your div in css:

 .divClass { display:table-cell; vertical-align:middle; } 

after that, your DIV element will act as TD elemnt from the table.

to align the image in a div with a percentage for the vertical position of the image Look at the link below (percentage value):

http://reference.sitepoint.com/css/vertical-align

+4
source

Give the div position:absolute and the image inside it position:relative with top:50% and the top margin is the negative half of the image height. This centers your image vertically.

 div{ border:1px solid red; width:400px; height:400px; position:relative; } img{ position:absolute; top:50%; margin-top:-64px; /*negative half image height */ } 

Check out the working example http://jsfiddle.net/qtL4n/

0
source

Source: https://habr.com/ru/post/1347845/


All Articles