Center image vertically with maximum height and maximum width

I have the following html code:

<div style="border: 3px coral solid;width:400px;height:400px;background:#D4D0C8;"> <img style="max-width:400px;max-height:400px;" src="myImage.jpg"> </div> 

Using these styles, images with a width> 400 pixels change but remain at the top of the div. Is there a way to vertically center them?

+6
source share
2 answers

CSS

 div { border: 3px solid coral; width: 400px; height: 400px; background: #d4d0c8; line-height: 400px; text-align: center; } img { max-width:400px; max-height:400px; vertical-align: middle; } 

See demo script .

+9
source

Well, I seem to have found where the problem is. The image is correctly centered by reference because it is inside an iframe. Inside a regular page stream, an image will be displayed at the top of its container.

As shown in table et: the table cell is broken down into IE, the fix requires a minimal table:

 <html> <head> <style type="text/css"> #content { border:solid 1px;} img{ max-width:400px;max-height:400px;margin:auto;} #page-table { height: 400px; width: 400px; border-collapse: collapse; text-align: center; border:solid 1px; } #page-td { height: 100%; padding: 0; vertical-align: middle; } div#content2{ border:solid 1px; width: 400px; height: 400px; /*line-height: 400px;*/ text-align: center; display: table-cell; vertical-align: middle; } img#image2 { max-width:400px; max-height:400px; vertical-align: middle; } div#enclosingdiv2 { border:solid 1px; } </style> </head> <body> With table: <table id="page-table"><tr><td id="page-td"> <div id="content"> <img src="http://lorempixum.com/250/250/abstract"> </div> </td></tr></table> Without: <div id="content2"> <div id="enclosingdiv2"> <img id="image2" src="http://lorempixum.com/250/250/abstract"> <div> </div> </body> </html> 
0
source

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


All Articles