June 14, 2011

100% DIV width is not really 100%

Question by Kevin

When I have a <div> with width: 100%, it is not really 100%:

<div id="div">testtesttesttesttest</div>

...

#div {
  width: 100%;
  background-color: red;
}

Now when you resize the window, so there is a horizontal scrollbar, and you scroll to the right, then the background is vanished. How can I remain the background in this case?

Here you can see the problem in action:
http://beta.ovoweb.net/?i=3

Now when you resize the window and scroll to the right, you can’t see the background anymore. How to fix this?

Answer by jsumners

The 100% value is 100% of the parent’s width or the view port. See the documentation.

Answer by Starx

Width: 100%, is highly affected by its margin and margin and padding of its parent (body in your case). SO, reset them first

Something like

body {
    margin: 0;
    padding: 0;
}
#div {
  margin: 0;
  width: 100%;
  background-color: red;
}

DEMO

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!