Center A Div Inside Anotehr Div

I have had to look this up so many times that I decided to just write down the solution. This is how to center a <div> element inside a <div> element.

(Truth be known I was much happier with the <center> tag. It was really obvious what it did. This is kind of unusual and weird.)

<div id="outer">
     <div id="inner">Stuff to Center</div>
</div>


This is the style to do the centering. The outer div has a width. The inner uses auto-margin to put itself into the center.

#outer {
    width: 100%;
}

#inner {
    display: table;
    margin: 0 auto;
} 

This works back to IE8 and I have tested it on FireFox, Chrome, Safari, Safari Mobile and Android.

The key is that you have to have a known width for the outer element.

A full example with red/gren borders around the divs to make it easier to see the results (testCenter.html):

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>

#outer {
	width: 100%;
}

#inner {
    display: table;
    margin: 0 auto;
} 

#outer {
	border: 1px solid red;
}

#inner {
	border: 1px solid green;
}

</style>
</head>
<body>

<div id="outer">
     <div id="inner">Stuff to Center</div>
</div>

</body>
</html>



•       •       •       •       •       •

Summary: # of Words: 227
Author: Philip Schlump
Published On: 2013-05-05

Download code from this articles in .tar.gz for Mac/Linux/Unix or .zip with CR/LF for Windows format.

 

Before You Go....

Have you read "Unintend Consinsequences"?

"I laughed so hard it hurt..."
    Rod Brown

"Incredibly funny! Incredibly true!"
    Tad Stevens