How to position image in the center/middle both vertically and horizontally

put the image in a <div> with text-align:center; without specifying the size of the box

<div class="picture_div" style="margin:0px auto; text-align:center;">
     <img src="media/BezierCurve.gif" />
</div>

alternatively you can specify width and the height of the <div> box in order to center the image (actually the div box).

<div id="blue" style="border:1px solid blue; width:100px; height:100px; margin:10px auto;">
    <img src="media/BezierCurve.gif" />
</div>

There are several ways to do this, and if it needs to work in all browsers (IE7+ and the rest) you need to do different things to make it work in some of the cases.

  1. Use absolute position. This only works if you know the size of the image. Here you set it to position: absolute; left: 50%; top: 50%; margin: -<half height of image> 0 0 -<half width of image>.

    See example here: http://jsfiddle.net/JPch8/

  2. Use margin: 0 auto;text-align: center; and line-height/font-size. This is a bit more tricky, since line-height doesn't work as it should in IE for inline-block elements like images. That's where the font-size comes in. Basically, you set the line-height of the image container to the same as the container's height. This will vertically align inline elements, but in IE you need to set the font-size instead to make it work.

    See example here: http://jsfiddle.net/JPch8/2/

  3. In modern browsers that support display: flex you can do it by simply setting the container div to display: flex; align-items: center; justify-content: center;

    See example here: https://jsfiddle.net/ptz9k3th/

Tags:

Html

Css