Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

<div id="photo_leftPanel" style="float: left; width: 604px; position: relative;">
<img src="bla.jpg">
</div>

How can i make the image start from the middle of this box? (middle both vertical and horizontal)

like image 686
Karem Avatar asked Feb 03 '11 15:02

Karem


People also ask

How do you center an element both vertically and horizontally?

You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.

How do you center an image in the middle of the page?

Step 1: Wrap the image in a div element. Step 2: Set the display property to "flex," which tells the browser that the div is the parent container and the image is a flex item. Step 3: Set the justify-content property to "center." Step 4: Set the width of the image to a fixed length value.


1 Answers

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/

like image 85
Martin Jespersen Avatar answered Oct 05 '22 17:10

Martin Jespersen