CSS: how to vertically and horizontally align an image?

There is a place for an image on my page, which can be, say, a maximum image of 100x100. Users can upload any image dimension, and the web application will resize it, supporting an aspect ration, up to 100x100. Thus, it is possible to resize images to, for example, 75x100 or 100x75, etc.

Regardless of the size of the resized, I want it to be displayed vertically and horizontally in the center in the selected space on the web page. How to do it in CSS? Do I need to contain a div, for example:

<div class="image_container">
     <image src="http://placehold.it/100x100/" height="100" width="100" alt=""/>
</div>

In any case, a CSS example will be helpful. Thank!

+6
source share
7 answers

- http://jsfiddle.net/zYx4g/ .

.image_container {
    width: 300px;
    height: 300px;
    background: #eee;
    text-align: center;
    line-height: 300px;
}

.image_container img {
    vertical-align: middle;
}
+21

, , flex

<div class="container">
    <img  src="http://placehold.it/200x200" />
</div>

CSS

.container {
    display: flex;
    justify-content: center;
    align-items: center;
    border: 1px solid;
    width: 50vw;
    height: 50vw;
}
.container img
{
    max-width:100%;
    max-height:100%;
}

Fiddle

, - flex, caniuse

+8

reset :

.image_container img{
    position: relative;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;
}
+3

:

.image_container {
    display:table-cell;
    overflow:hidden;
    text-align:center;
    vertical-align:middle;
}
.image_container img {
    vertical-align:baseline;
}

100%, . : http://jsfiddle.net/fJtwX/1/

+1

: .

Jamie , , , ?

I know that I probably want to groan, but there is nothing wrong with tables when used where necessary!

http://jsfiddle.net/Yhq5h/11/

set your container depending on the size, I will need to see the page, but this should work on all browsers.

+1
source

In case someone still needs this way to do this with a mapping table;

.thumbnail { width:150px; height:150px; display: table; }

.thumbnail img { max-width:150px; max-height:150px; }

.thumbnailcontainer { display:table-cell; vertical-align: middle; text-align:center;}
<article class="thumbnail">    
  <div class="thumbnailcontainer">
         <img id="Img1" src="http://img.youtube.com/vi/QAOMIH7cgh0/0.jpg" />   
   </div>
</article>
Run codeHide result
0
source
<div class="blog-thumbnail">                
    <img src="img.jpg" alt="img">
</div>

.blog-thumbnail {
    height: 200px;
    margin: 0 auto;
    position: relative;
}
.blog-thumbnail img {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    top: 0;
    margin: auto;
    max-width: 100%;
    max-height: 100%;
}
0
source

All Articles