How to Position Images In Div's Middle Vertically


Time after time I run into problem, that i need to position image or some container in middle vertically. I have found method for this, which is short and easy. but unfortunatly works only with elements with same height. but you can allways use some javaScript, so it becomes universal.
JavaScript would be used to set margins.


Method - with absolute position 50% from top. Used for elements with fixed heights.


<div class="container">
    <img src="">


.container {
    height: 100px;
    width: 100px;
    position: relative;
    background-color: darkgray;

img {
    height: 20px;
    width: auto;
    position: absolute;
    margin: -10px 0 0 0;
    top: 50%;

What happened there? In relative positioned div we put an image which positioned absolute 50% from top. Since 50% is measured from images top, we need to add negative margin to top, which is exactly half of elements height. With this trick image is exactly in middle.