Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background color does not show up when scrolling to the right

Tags:

html

css

scroll

I have the following simple HTML and CSS:

<html>
<head>
    <title></title>
</head>
<body>
    <div style="width: 970px;">Text area</div>
    <div style="height: 20px; background-color:gray; width: 100%; "></div>
</body>
</html>

I load this page in a browser. If the width of the browser is 400px (just an example), then I see a horizontal scroll bar in the browser screen bottom. If I move the scroll bar to the right, I can see that the background of the second div does not extend to the right.

I hope that the background color of the second div can extend from browser's left edge to the right edge (no matter what the width of the browser is).

How can I fix this?

Thanks!

like image 786
curious1 Avatar asked Sep 11 '25 04:09

curious1


2 Answers

This is because the body tag's width is the width of your browser window, and the 100% width on the second div is taking the width of the parent, which is the body tag. In your example this means the second div will only ever be 400px (the width of the browser window).

You'll have to set the width of the body tag to also be 970px in order for this to work. Setting body to 100% width won't solve it, because that will take 100% of it's parent width which is the html tag and will still be the width of the browser window.

<body style="width: 970px;">
    <div style="width: 970px;">Text area</div>
    <div style="height: 20px; background-color:gray; width: 100%; "></div>
</body>

EDIT: An alternative is to set the body to have display: inline-block which will force it to expand to the width of it's children:

<body style="display:inline-block">
    <div style="width: 970px;">Text area</div>
    <div style="height: 20px; background-color:gray; width: 100%; "></div>
</body>
like image 183
Dave Zych Avatar answered Sep 12 '25 19:09

Dave Zych


You can solve like this:

<div style="width: 970px">
  <div>Text area</div>
  <div style="height: 20px; background-color:gray; width: 100%;"></div>
</div>
like image 32
Beterraba Avatar answered Sep 12 '25 18:09

Beterraba