How to Center Horizontally a Position Fixed Element with CSS?

24 Apr 2012

The common approach is width:100px; left:50%; margin-left:-50px which is simple but will only work with fixed width. Here is how to do it in a more flexible way.

The CSS:

.container { 
	/* fixed position a zero-height full width container */
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	height: 0;
	/* center all inline content */
	text-align: center;
}

.container > div {
	/* make the block inline */
	display: inline-block;
	/* reset container's center alignment */
	text-align: left;
}

…and HTML:

<div class="container">
	<div>I will always be at the top center.</div>
</div>

Tested on recent Chrome, Firefox, iOS 5, Android 4, IE9. Should work in every browser that supports inline-block. Try it on the demo page.