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 come across this page, but it looks like this problem was caused by not applying text-align: center
.
You 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.com/eric/tools/css/reset/
You ask in the comment 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 combat 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With