Center image of fluid in a fluid container vertically

Of course, I don’t want to add CSS issues to the bunch of vertical alignments, but I spent hours trying to find a solution until it helped. Here's the situation:

I am creating a slideshow image gallery. I want the images to be displayed as strongly as the user window allows. So, I have this external placeholder:

<section class="photo full"> 

(Yes, I use HTML5 elements). Which has the following CSS:

 section.photo.full { display:inline-block; width:100%; height:100%; position:absolute; overflow:hidden; text-align:center; } 

Then the image is placed inside it. Depending on the orientation of the image, I set either the width or the height to 75%, and the other axis is auto:

 $wide = $bigimage['width'] >= $bigimage['height'] ? true: false; ?> <img src="<?= $bigimage['url'] ?>" width="<?= $wide? "75%" : "auto"?>" height="<?= $wide? "auto" : "75%"?>"/> 

So, we have a liquid outer container, inside of which is a liquid image. Horizontal centering the image works, but I can't find a way to vertically center the image inside the container. I researched centering methods, but most assume the container or image has a known width or height. Then there is the display: the table-cell method, which doesn't seem to work for me either.

I am stuck. I am looking for a CSS solution, but I am also open to js solutions.

+4
source share
3 answers

This works great:

 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 assume that the display table-cell did not work for you, because the parent container did not appear as a table.

Here is a demo in jsfiddle:

http://jsfiddle.net/duopixel/5wzPS/

+8
source

Maybe this works for you (a div is a div wrapped around your image):

 div { display: table-cell; vertical-align: middle; text-align: center; } 

Execution example.

+1
source

Let him skip the whole stupid table! :)

 <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/

0
source

Source: https://habr.com/ru/post/1338588/


All Articles