tags:

views:

3458

answers:

6

Quite a "simple" problem here and not sure why it's being so complicated.

  1. Have a 100% (width) sized div.
  2. Have another div positioned in the middle of this div (sized 940px width)

Any ideas? :)

+10  A: 

The below style to the inner div will center it.

margin: 0 auto;
Virat Kadaru
+6  A: 
.parent { text-align: center; }
.parent > .child { margin: 0 auto; width: 900px; }
geowa4
I was missing the text-align it seems as i had the margin and wasn't working. Accepted, cheers.
Shadi Almosri
text-align:center does not help with centering the inner div.
Vizjerai
centers the stuff (text) inside though, resulting in the same desired outcome (if you only have text). for auto-margin to work, you also need a width on the inner div.
geowa4
The child selector > won't work in IE6, in case you care.
ScottE
+1  A: 

Just add margin: 0 auto; to the inside div.

ScottE
+4  A: 

The key is the margin: 0 auto; on the inner div. A proof-of-concept example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<body>
    <div style="background-color: blue; width: 100%;">
     <div style="background-color: yellow; width: 940px; margin: 0 auto;">
      Test
     </div>
    </div>
</body>
</html>
Larsenal
This is a good answer as it's crucial to have the right doc type if you're using the margin: 0 auto technique
ScottE
+2  A: 

for detail info, let's say the code below will make a div aligned center:

margin-left: auto;
margin-right: auto;

or simply use:

margin: 0 auto;

but bear in mind, the above CSS code only works when you specify a fixed width (not 100%) on your html element. so the complete solution for your issue would be:

.your-inner-div {
      margin: 0 auto;
      width: 900px;
}
Khashayar
This is a great example because you correctly explicitly point out that a width on the inner div is required.
Bill Ayakatubby
A: 

"margin: 0 auto; width: 900px; "

The above works - thanks

Suchet