When will Margin: auto; work and not work?

Is this an issue in regards to block and inline elements?

It can be frustrating having to use margin-left to center things sometimes.

When margin:auto doesn’t work, is using margins the only or best alternative?

Hi,

Yes it has to do with the differences between block and inline elements but also block elements need a width before auto margins will work. Block elements can have dimensions applied but inline elements can’t (elements with inline-block and and most replaced elements like images and buttons can also have a width applied but will not center with auto margins).

So to center a block element just give it a width and then use margin:0 auto (or just margin:auto although that won’t reset the default top/bottom margins in some very old IE browsers).

For inline elements (and inline-block elements) you can just text-align:center on the parent and the text will be centred. If you use a left margin on an inline element then that margin only apples on the line that the text/element is on. If the line wraps there will be no margin on the subsequent lines.

Note that you can’t use auto margins on floats as that makes no sense and has no effect.

margin:auto won’t work when you have a float or haven’t specified a width.

Some methods I can think of are:

.centering { /* centering an inline element with display:block */
	display: block;
	margin: auto;
	width: 50%;
}

.centering2 {
	margin: auto;
	width: 80%;
}

.centering3 { /* centering with off-screen positioning */
	position: relative;
	left: -50%;
	float: right;


}

.centering3 .inner { /* dragging it back into focus */
	position: relative;
	left: 50%;
}

.centering4 { /* centering with display:table */
	display: table;
	margin: auto;
}

		<a class="centering" href="">Centering an inline element.</a>
		<div class="centering2">
			<p>Centering a block-level element.</p>
		</div>
		<div class="centering3">
			<p>Centering with positioning and floats.</p>
		</div>
		<div class="centering4">
			<div class="inner">
				<p>Centering with display:table.</p>
			</div>
		</div>
1 Like

Thanks. The last one working for me.