HTML:
Some content
CSS:
body {
margin: 0 auto;
width: 470px;
back
Into browser, the <body></body>
represent the main container and width is referred to browser.
If you want center all content into body can simply try something so:
body {
margin: 0px auto;
text-align: center;
background-color: cyan;
}
<body>
<p> Content </p>
</body>
I prefer include the content into <div></div>
.
The body actually is taking that width, and it is centering. It's just a CSS quirk that makes the background occupy the whole page rather than the space actually occupied by the body element.
A way to fix this is to include a background
property on the html
tag.
Here's an example.
However, as mentioned by others, this probably isn't something you want to do. It's better to add a div
within the body and style that.
Your CSS is applying those property on the whole page.
Maybe you were looking for this:
p { //body changed to p
margin: 0 auto;
width: 470px;
background-color: cyan;
}
Here is the updated JSFiddle
When the <html>
element has no specified background the body background will cover the page. If the html element does have a background specified on it, the body background will behave like any other element.
From the W3:
For HTML documents, however, we recommend that authors specify the background for the BODY element rather than the HTML element. For documents whose root element is an HTML "HTML" element or an XHTML "html" element that has computed values of 'transparent' for 'background-color' and 'none' for 'background-image', user agents must instead use the computed value of the background properties from that element's first HTML "BODY" element or XHTML "body" element child when painting backgrounds for the canvas
So essentially your code is fine and the content is centered, but the background you specified on the body is being applied to the <html>
as well. You can see the difference when you give the <html>
element a white background:
jsFiddle example
You're treating the body
like a <div>
element. This is causing the text to be centered. Instead enclose your
<p>Some content</p>
inside a <div>
and maybe give it a class
HTML:
<body>
<div class="name"
<p>Some content</p>
</div>
</body>
CSS:
.name{
margin: 0 auto;
width: 470px;
background-color: cyan;
text-align: center;
}
if you don't want to use a class
or id
or <div>
you can simple change all <p>
to that css
CSS:
p{
margin: 0 auto;
width: 470px;
background-color: cyan;
text-align: center;
}
You can't set a width on body, it's defined by the browser size. Edit your html to contain inner content, and it will work fine.
This:
<body>
<div id="content">
<p>Some content</p>
</div>
</body>