I have the following code which sets up a container which has a height that changes with the width when the browser is re-sized (to maintain a square aspect ratio).
Make another div and add both 'dummy' and 'img-container' inside the div
Do HTML and CSS like follows
html , body {height:100%;}
.responsive-container { height:100%; display:table; text-align:center; width:100%;}
.inner-container {display:table-cell; vertical-align:middle;}
<div class="responsive-container">
<div class="inner-container">
<div class="dummy">Sample</div>
<div class="img-container">
Image tag
</div>
</div>
</div>
Instead of 100% for the 'responsive-container' you can give the height that you want.,
html code
<div class="image-container">
<img src=""/>
</div>
css code
img
{
position: relative;
top: 50%;
transform: translateY(-50%);
}
You can center an image, both horizontally and vertically, using margin: auto
and absolute positioning. Also:
.responsive-container {
margin: 1em auto;
min-width: 200px; /* cap container min width */
max-width: 500px; /* cap container max width */
position: relative;
overflow: hidden; /* crop if image is larger than container */
background-color: #CCC;
}
.responsive-container:before {
content: ""; /* using pseudo element for 1:1 ratio */
display: block;
padding-top: 100%;
}
.responsive-container img {
position: absolute;
top: -999px; /* use sufficiently large number */
bottom: -999px;
left: -999px;
right: -999px;
margin: auto; /* center horizontally and vertically */
}
<p>Note: images are center-cropped on <400px screen width.
<br>Open full page demo and resize browser.</p>
<div class="responsive-container">
<img src="http://lorempixel.com/400/400/sports/9/">
</div>
<div class="responsive-container">
<img src="http://lorempixel.com/400/200/sports/8/">
</div>
<div class="responsive-container">
<img src="http://lorempixel.com/200/400/sports/7/">
</div>
<div class="responsive-container">
<img src="http://lorempixel.com/200/200/sports/6/">
</div>
Use this css, as you already have the markup for it:
.img-container {
position: absolute;
top: 50%;
left: 50%;
}
.img-container > img {
margin-top:-50%;
margin-left:-50%;
}
Here is a working JsBin: http://jsbin.com/ihilUnI/1/edit
This solution only works for square images (because a percentage margin-top value depends on the width of the container, not the height). For random-size images, you can do the following:
.img-container {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* add browser-prefixes */
}
Working JsBin solution: http://jsbin.com/ihilUnI/2/edit