Align image in center and middle within div
I have following div
<div id="over" style="position:absolute; width:100%; height:100%>
<img src="img.png">
</div>
How to align the image so as to be located in the middle and center of div ?
Solution 1:
body {
margin: 0;
}
#over img {
margin-left: auto;
margin-right: auto;
display: block;
}
<div id="over" style="position:absolute; width:100%; height:100%">
<img src="http://www.garcard.com/images/garcard_symbol.png">
</div>
JSFiddle
Solution 2:
<div style="display:table-cell; vertical-align:middle; text-align:center">
<img src="img.png">
</div>
Solution 3:
This can also be done using the Flexbox layout:
STATIC SIZE
.parent {
display: flex;
height: 300px; /* Or whatever */
background-color: #000;
}
.child {
width: 100px; /* Or whatever */
height: 100px; /* Or whatever */
margin: auto; /* Magic! */
}
<div class="parent">
<img class="child" src="https://i.vimeocdn.com/portrait/58832_300x300"/>
</div>
DYNAMIC SIZE
html, body {
width: 100%;
height: 100%;
display: flex;
background-color: #999;
}
* {
margin: 0;
padding: 0;
}
.parent {
margin: auto;
background-color: #000;
display: flex;
height: 80%;
width: 80%;
}
.child {
margin: auto; /* Magic! */
max-width: 100%;
max-height: 100%;
}
<div class="parent">
<img class="child" src="https://i.vimeocdn.com/portrait/58832_300x300"/>
</div>
I found the example in this article, which does a great job explaining the how to use layout.