cybermonkey cybermonkey - 5 months ago 14
CSS Question

Why are my CSS centring styles being ignored?

I have the following HTML & CSS:



body {
font-size: 16px;
overflow: scroll;
}
html {
position: absolute;
min-height: 100%;
}
.mainContainer {
position: absolute;
padding-top: 40px;
margin: 0px auto;
width: 1200px;
}
.mainpagetitleContainer {
position: absolute;
padding-top: 20px;
}
.mainpagetitle {
font-size: 4em;
font-weight: 300;
margin: 0px auto;
}
.mainpagetitleContainer > .subtitle {
color: #333;
width: 400px;
margin: 0px auto;
font-size: 1.2em;
font-weight: 300;
}

<div class="mainContainer">
<div class="mainpagetitleContainer">
<div class="mainpagetitle">
Text.
</div>
<div class="subtitle">
Text.
</div>
</div>
</div>





I am attempting to centre my divs as outlined in this answer to Horizontally center a div in a div, however my divs seem intent on being stuck to the left-hand side of the page rather than the centre.

The idea is to have a background and a central column to the page, like so:

enter image description here

I tried messing with
margin: 0px auto;
to no effect.

What am I doing wrong, and how can I fix this?

Answer

To center divs horizontally using margin: 0 auto, you should use position relative on container and on inner divs.

Try something like this:

body {
  font-size: 16px;
  overflow: scroll;
}
html {
  position: relative;
  min-height: 100%;
}
.mainContainer {
  position: relative;
  padding-top: 40px;
  margin: 0px auto;
  width: 1200px;
}
.mainpagetitleContainer {
  position: relative;
  padding-top: 20px;
}
.mainpagetitle {
  font-size: 4em;
  font-weight: 300;
  margin: 0px auto;
}
.mainpagetitleContainer > .subtitle {
  color: #333;
  width: 400px;
  margin: 0px auto;
  font-size: 1.2em;
  font-weight: 300;
}

To understand more about layout in CSS, I recommend reading this site: http://learnlayout.com/toc.html