Tsukimoto Mitsumasa
Tsukimoto Mitsumasa

Reputation: 582

How to center the contents of the web page inside the body tag using CSS or jquery?

I know this sounds odd but I met this problem in which I cannot center the elements inside the <body> tag. I already used margin: 0px auto; but still nothing works. Is there a way I can make it by using jquery? Thanks

This is my code in my .css file

body {
margin: 0px auto !important;
background:#FFFFFF;
font-family:Arial;
font-size:12px;
}

Upvotes: 0

Views: 798

Answers (5)

Ben
Ben

Reputation: 11208

Fairly simple.

body {
 text-align:center; /* ie */}
div#website_container {
 width:960px;
 margin:0 auto; /* others */
 text-align:left;}

Then start creating your site within the div website_container.

Upvotes: 0

Christoph
Christoph

Reputation: 51221

Setting auto margin works, but it needs a fixed on that element in order to work.

<your-element>{
   width:200px;
   margin:0 auto;    
}​

If you want to center several elements you can either set width and margin on all of those, or cleaner - introduce a wrapper element which holds all your elements you want to center and declare the width and margin on that element. This has the advantage that you only need to declare the width once, making it easier to change it later.

Upvotes: 1

Ahsan Khurshid
Ahsan Khurshid

Reputation: 9469

Set margin: 0px auto; on the element which you want to make center.

Example:

  body{
      width: 100%;
  }

  .aDiv {
     width: 200px;
     height: 200px;
     margin: 0 auto;
  }

SEE DEMO

Edited:

As OP stated in his comments, that;

He want to center all the elements inside the body.

So I suggest to set margin: 0px auto; on all element which you want to make center.

SEE EXAMPLE

Upvotes: 1

Alfred
Alfred

Reputation: 21406

You may make a div inside your parent <body>, give it a specific width, and then centre it by giving auto left and right margins.

for example;

.test{
    background: #06C;
    margin-left: auto;
    margin-right: auto;
    height: 100px;
    width: 80%; /* or you may give it in px like 100px */
}

Here is the live demo

Upvotes: 0

Maverick Jones
Maverick Jones

Reputation: 434

You should be able to centre the contents simply using the CSS:

 body{text-align:center;}

but if you've already done that with no effect try using padding on either side of the child elements, so they are positioned in the centre.

 body{text-align:center; padding-left:20%; padding-right:20%;}

If you're still having problems, make sure that the elements you are trying to centre aren't set to position:relative; or position:absolute;

Upvotes: 0

Related Questions