www.data-blogger.com
www.data-blogger.com

Reputation: 4164

100% DIV width is not really 100%

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?

Upvotes: 36

Views: 125248

Answers (9)

GaurabDahal
GaurabDahal

Reputation: 876

Most of the I time add this bit of code to my css. It should work for you too. Yes, 100% width or height is always based on the parent container.

CSS

* {
  margin: 0;
  padding: 0;
}

html,
body {
  height: 100%;
  width: 100%;
}

#container {
  width: 100%;
  height: 100%;
  background: gray;
  position: relative;
  display: block;
}

#content {
  height: 50px;
  width: 50px;
  bottom: 20px;
  right: 10%;
  background: red;
  position: absolute;
}

HTML

<div id="container">
  <div id="content"></div>
</div>

OUTPUT

enter image description here

Upvotes: 1

Satwik Gupta
Satwik Gupta

Reputation: 1

If you have row included in your class then it sometimes causes problems, remove it and add it inside a new div

Upvotes: 0

RivkaZ
RivkaZ

Reputation: 91

check if you have this code in the div or it parent:

 #div  {
    max-width: 300px;
}

or

 #div  {
    max-width: 50%;
}

This cause the width not to be 100% of the page. Just remove it.

Upvotes: 1

James in Indy
James in Indy

Reputation: 2884

In my case, the div tag did not take up 100% of its parent tag because the div had a display of "inline." Changing it to "inline-block" fixed that problem.

Upvotes: 1

shane
shane

Reputation: 239

This oughta do it (add this line to the very top of your CSS file):

* { margin: 0; padding: 0; }

Works all the time for me.

Upvotes: 3

Arda
Arda

Reputation: 6926

add this to css:

html, body {
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
}

Then it should work.

Upvotes: 5

Dan
Dan

Reputation: 1244

100% is only 100% of the available width, based on the parent container. So if you create a DIV with width 500 pixels, then nest another DIV inside with width 100%, your 100% DIV can expand to a maximum of 500 pixels (not counting any padding or margin so you need to reset them to 0).

Upvotes: 2

Starx
Starx

Reputation: 78991

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

Upvotes: 23

James Sumners
James Sumners

Reputation: 14777

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

Upvotes: 35

Related Questions