Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto margins don't center image in page

In this example the image is not centered. Why? My browser is Google Chrome v10 on windows 7, not IE.

<img src="/img/logo.png" style="margin:0px auto;"/>
like image 596
Web_Designer Avatar asked Apr 20 '11 17:04

Web_Designer


People also ask

Why is my margin auto not centering?

Important: The reason your margin: auto; is not centering is because you haven't set a fixed width to the element you're trying to center. We also specify text-align: center; as this will center the text inside the inner container.

How do you center an image using margin auto?

To center an image, we have to set the value of margin-left and margin-right to auto and make it a block element by using the display: block; property. If the image is in the div element, then we can use the text-align: center; property for aligning the image to center in the div.

Does margin auto work on images?

Another way to center an image is by using the margin: auto property (for left-margin and right-margin). However, using margin: auto alone will not work for images.

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.


4 Answers

add display:block; and it'll work. Images are inline by default

To clarify, the default width for a block element is auto, which of course fills the entire available width of the containing element.

By setting the margin to auto, the browser assigns half the remaining space to margin-left and the other half to margin-right.

like image 99
Ross Avatar answered Oct 20 '22 00:10

Ross


You can center auto width div using display:table;

div{
margin: 0px auto;
float: none;
display: table;
}
like image 41
sameeuor Avatar answered Oct 20 '22 02:10

sameeuor


Under some circumstances (such as earlier versions of IE, Gecko, Webkit) and inheritance, elements with position:relative; will prevent margin:0 auto; from working, even if top, right, bottom, and left aren't set.

Setting the element to position:static; (the default) may fix it under these circumstances. Generally, block level elements with a specified width will respect margin:0 auto; using either relative or static positioning.

like image 14
Brendan Avatar answered Oct 20 '22 00:10

Brendan


In my case the problem was that I had set min and max width without width itself.

like image 11
Daniel Sitarz Avatar answered Oct 20 '22 01:10

Daniel Sitarz