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).
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 */
}
Note: images are center-cropped on <400px screen width.
Open full page demo and resize browser.