I've been facing this problem many times and I decided to ask. When I use relative positioning with width:100%
, the content doesn't go edge to edge of the screen. On the other hand, when I use absolute or fixed positioning, the content does go edge to edge. Why is this? Here's a sample code to show my problem:
#container {
display: block;
width: 100%;
position: relative;
height: 150px;
border: 1px solid;
text-align: center;
}
<div id='container'>
<br />
<br />^
<br />
<- Why do I have these spaces? ->
<br />\/
</div>
I've been facing this problem many times and I decided to ask. When I use relative positioning with width:100%
, the content doesn't go edge to edge of the screen. On the other hand, when I use absolute or fixed positioning, the content does go edge to edge. Why is this? Here's a sample code to show my problem:
#container {
display: block;
width: 100%;
position: relative;
height: 150px;
border: 1px solid;
text-align: center;
}
<div id='container'>
<br />
<br />^
<br />
<- Why do I have these spaces? ->
<br />\/
</div>
Result:
What I want:
While Googling, I did e across this page, but it looks like this problem was caused by not applying text-align: center
.
-
1
You need to look up
padding
andmargin
. – Sani Huttunen Commented Nov 17, 2014 at 19:24
2 Answers
Reset to default 9You have to reset default body
margin / padding.
box-sizing: border-box;
will also help to include border size in width calculation.
body {
margin: 0;
padding: 0;
}
#container {
display: block;
width: 100%;
position: relative;
height: 150px;
border: 1px solid;
text-align: center;
box-sizing: border-box;
}
<div id='container'>
<br />
<br />^
<br />
<- Why do I have these spaces? ->
<br />\/
</div>
Reference: body
Typical default display properties - box-sizing
I second emmanuel's response, and the ultimate answer is to clear all default styles with a CSS reset: http://meyerweb./eric/tools/css/reset/
You ask in the ment why there is a non-zero value for margin and padding there. There are lots of styles in place by default in your browser such as font-sizes and weights on headings, list style types, etc..
The problem is that browsers don't always render these default styles precisely the same. To bat this, many people have been using a CSS reset (Eric Meyer's version above is the canonical one) that clears out every default style. Be careful the first couple of times you do this, however, because it really clears out everything. This means no padding on ul
tags, no padding on anything, no numbers on ol
items.