CSS: how to vertically and horizontally align an image?

后端 未结 7 906
青春惊慌失措
青春惊慌失措 2020-12-31 12:27

My page has space for an image that can be, say, a maximum 100x100 image. Users can upload any image dimension and the web application will resize it, maintaining aspect rat

相关标签:
7条回答
  • 2020-12-31 12:50

    I know this is and old question already answered but now you can use 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 Demo

    you can also customize the size of your container, some browser may not support flex you can check it here caniuse

    0 讨论(0)
  • 2020-12-31 12:51

    In case someone still needs this here's a way to do it with display 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>

    0 讨论(0)
  • 2020-12-31 12:53

    Try this - http://jsfiddle.net/zYx4g/ This will work on image of any size and in all browsers.

    .image_container {
        width: 300px;
        height: 300px;
        background: #eee;
        text-align: center;
        line-height: 300px;
    }
    
    .image_container img {
        vertical-align: middle;
    }
    ​
    
    0 讨论(0)
  • 2020-12-31 13:00

    Move your left top corner of the image to the middle and reset it half the image's width and height:

    .image_container img{
        position: relative;
        top: 50%;
        left: 50%;
        margin-top: -50px;
        margin-left: -50px;
    }
    
    0 讨论(0)
  • 2020-12-31 13:00

    Edit: Zoltan Toth answered nicely.

    Jamie's answer works, if you want older browserer compatibilty then use a table?

    I know i'll probably get moaned at, but theres nothing wrong with tables when used where needed!

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

    set your container up what ever size is needed, I'd need to see the page, but this should work on all browsers.

    0 讨论(0)
  • 2020-12-31 13:10

    You could try this:

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

    Not 100% sure on browser compatibility, but should get you started in the right direction. Example: http://jsfiddle.net/fJtwX/1/

    0 讨论(0)
提交回复
热议问题