mango
mango

Reputation: 1223

How to place body at center of page regardless of screen size

How do I ensure that my content is always at the center of the page? I set the min and max width and height to a fixed number of pixels and placed the body at margin-left: 32%. But when I change the browser size the body shifts away from the center. Is there another to make sure everything stays at the center?

Upvotes: 0

Views: 2213

Answers (4)

StijnEversdijk
StijnEversdijk

Reputation: 11

Applying margin: 0 auto on a wrapper is the most common way of centering elements. To be sure your content is always at the center of your screen, wrap it in a container div, specify a width(for RWD percentages are the most usefull). With margin: 0 auto you almost can't go wrong, but there is another way that also works really well.

You can use position: relative; and css3's translate to center your content. If you use percentages for the positioning and the translate, it never can go wrong.

Basic code:

<body>
  <div id="wrapper">
    The content
  </div>
</body>

CSS(written in Sass):

div#wrapper
  width: 75% // can be whatever you use
  position: relative
  left: 50%
  +translateX(-50%)

+translateX() is a Compass mixin for

 transform: translateX();

I've made a pen with an example: http://codepen.io/stijneversdijk/pen/hlICH

Good luck!

Upvotes: 1

Eduardo La Hoz Miranda
Eduardo La Hoz Miranda

Reputation: 2056

Please note you should use the margin: 0 auto only on the actual container of your content. Usually it is used like:

body{
background: red;
}

.container{
background: green;
margin: 0 auto;
width: 960px;
overflow: auto;
}

For this the html in the body would look like

<body>
<div class="container">
    ****your content****
</div>
</body>

Upvotes: 1

Zzyrk
Zzyrk

Reputation: 905

Try using the following:

margin:0 auto;

Upvotes: 2

Guy
Guy

Reputation: 764

Don't set margin-left to a percent on the body tag, it'll only be center for a specific screen size. Instead in your css file set:

body{margin:0 auto;}

Here’s an example

Upvotes: 2

Related Questions