Vertically center a fluid image in a fluid container
-
29-10-2019 - |
Question
I certainly do not want to add to the pile of vertical alignments CSS questions, but I've spent hours trying to find a solution to no avail yet. Here's the situation:
I am building a slideshow gallery of images. I want the images to be displayed as large as the user's window allows. So I have this outer placeholder:
<section class="photo full">
(Yes, I'm using HTML5 elements). Which has the following CSS:
section.photo.full {
display:inline-block;
width:100%;
height:100%;
position:absolute;
overflow:hidden;
text-align:center;
}
Next, the image is placed inside it. Depending on the orientation of the image, I set either the width or height to 75%, and the other axis to auto:
$wide = $bigimage['width'] >= $bigimage['height'] ? true: false; ?>
<img src="<?= $bigimage['url'] ?>" width="<?= $wide? "75%" : "auto"?>" height="<?= $wide? "auto" : "75%"?>"/>
So, we have a fluid outer container, with inside a fluid image. The horizontal centering of the image works, yet I cannot seem to find a way to vertically center the image within it's container. I have researched centering methods but most assume either the container or image has a known width or height. Then there is the display:table-cell method, which does not seem to work for me either.
I'm stuck. I'm looking for a CSS solution, but am open to js solutions too.
Solution
This works out fine:
section.photo.full {
display: table;
width: 100%;
height: 100%;
position: absolute;
overflow: hidden;
text-align: center;
}
section.photo.full a {
outline: 0;
display: table-cell;
vertical-align: middle;
}
section.photo.full img {
margin-top: 0;
}
I'm guessing display table-cell hadn't worked for you because it's parent container wasn't displayed as a table.
Here is a demo in jsfiddle:
OTHER TIPS
Maybe this works for you (div
is the div wrapped around your image):
div {
display: table-cell;
vertical-align: middle;
text-align: center;
}
Let's skip all of the table nonsense! :)
<div>
<img src="https://placehold.it/1000x1000">
</div>
div {
position: relative;
}
img {
position: absolute;
width: 70%;
top: 50%;
left: 50%;
transform: translate3d(-50%,-50%,0);
}
Example: https://jsfiddle.net/te29m9fv/1/