Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative positioning at width 100% doesn't make the content go edge to edge

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: enter image description here

What I want: enter image description here

While Googling, I did come across this page, but it looks like this problem was caused by not applying text-align: center.

like image 550
Tetsudou Avatar asked Dec 19 '22 09:12

Tetsudou


2 Answers

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

like image 147
emmanuel Avatar answered Mar 09 '23 00:03

emmanuel


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.

like image 37
Barry T. Smith Avatar answered Mar 08 '23 23:03

Barry T. Smith