0

I need an image horizontally and vertically aligned centre inside a div element.

Guys Please post your codes to position an image inside a div element horizontally and vertically aligned centre. Please specify what should be the display property of parent div too. sample code : <div id="box"> <img id="image"/> </div>

21st Nov 2016, 5:28 AM
NIKHIL CM
NIKHIL CM - avatar
3 Réponses
+ 3
With flexboxes. div#box { display: flex; display: -webkit-flex; flex-direction: column; } img#image { margin: auto; align-items: flex-end; } See this: https://code.sololearn.com/W7cflT0ncFNJ
8th Dec 2016, 6:48 PM
$machitgarha
$machitgarha - avatar
+ 3
Using one container more, you can use 'display' property to recreate a 'table' context (without the semantical meaning of <table> wich is not good suited for layout purpose ;P): <div id="box"> <div> <img> </div> </div> #box { display:table; width:100%; /* set explicit size to avoid container to fit to picture size */ height:100%; /* be carreful that parent need to have explicit height also, else 100% of parent height will be 100% of itself height... or set absolute unit */ } #box > div { display:table-cell; vertical-align:middle; text-align:center; } #box > div > img { /* not required, but to be sure that your image doesn't be too much big sized to be centered ^^ */ max-width: 50%; /* max-height could be used also, but only one, else your image will not preserve aspect ratio :P */ }
4th Sep 2017, 7:13 AM
visph
visph - avatar
+ 1
you can use flex box for this. Here's the style rule: div { display: flex; justify-content: center; align-items: center; } Thats it! This is the simplest you can do. however flexbox is not supported in older versions of internet explorer. You can use this code as long as you think you dont need a support for IE 8 or 9 . Thanks.
21st Nov 2016, 6:19 AM
Ruchi
Ruchi - avatar