How can I center <img> horizontally and vertically in a <div>?

I do not want to center the div, I want the contents of the div to be centered. I would like horizontal and vertical alignment.

Sorry if this is too easy or something else, but it's kind of a hassle to figure it out.

Grae

I am using IE7

+3
source share
5 answers

If you know the height and width of your image, place it absolutely, set the top / left side to 50%, and the top / left side to the negative half of the height / width of your image.

#foo {
    position:relative; /* Ensure that this is a positioned parent */
}
#foo img {
    width:240px;
    height:200px;
    position:absolute;
    left:50%;
    top:50%;
    margin-left:-120px;
    margin-top:-100px;
}

Real-time example: http://jsfiddle.net/Zd2pz/

+2
source

, , div, jquery div, , .

, , .

, , - , @simshaun @Prhogz

EDIT:

script

<script type="text/javascript" src="<%: Url.Content( "~/_assets/js/jquery.center.min.js" )%>"></script>

, DIV, ,

$(document).ready(function() {
    $("#myDIV").center({ vertical: false });
});
+2

text-align:center;

For vertical alignment, see, for example, W3 Style Guide

0
source

If you know in advance the height of the inner element,

CSS

.container {
    text-align: center; /* Center horizontally. */

    /* For demo only */
    border: 1px solid #000;
    height: 500px;
    margin: 20px;
    width: 700px;
}

.container img {
    margin-top: -167px;
    position: relative;
    top: 50%;
}

HTML:

<div class="container">
    <img src="http://farm6.static.flickr.com/5004/5270561847_7223069d5e.jpg" width="500" height="334" alt="">
</div>

Example

0
source

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


All Articles