bytecode77
bytecode77

Reputation: 14840

CSS width 100% limited to browser window (it doesn't extend to right scrolling area)

This site is full-width and adapts to the size of the browser window. However, once the browser window is smaller than the content displayed, the title gets cut off once you scroll to the right.

The default width of 100% seems to be working for the width of the browser window only, not the width of the page! The same also seems to apply on the vertical axis.


Example

#title
{
  height: 50px;
  color: white;
  background-color: #404040;
}
#content
{
  width: 800px;
  background-color: #f0f0f0;
}
<div id="title">
    TITLE
</div>
<div id="content">
    CONTENT
</div>


Actual result

This is what it looks like when the page is scrolled to the left

1

2

(For the sake of simplicity and privacy, content irrelevant to the question is censored.)

Upvotes: 4

Views: 3401

Answers (3)

BenThuro
BenThuro

Reputation: 21

For me it worked with this two little friends:

width: auto;
min-width: 100%;

No positon: fixed/absolute needed

Upvotes: 0

bytecode77
bytecode77

Reputation: 14840

After fiddling a lot with positioning, I eventually came up with something.

body
{
    position: absolute;
    min-width: 100%;
    min-height: 100%;
}

#menu-background
{
    z-index: -1;
    position: absolute;
    width: 250px;
    height: 100%;
    background-color: #404040;
}

and the menu background HTML

<div id="menu-background"></div>

<body> needs absolute positioning, otherwise the table of the content div will overflow out of the content div. Also, it needs a min-width of 100% to cover both cases: Either the window is smaller, or it's larger.

The menu works the same way, except that it is a single <div> that spans the entire page.


This solution works perfectly for both X and Y (menu and title) stretching and background color.

Upvotes: 2

Michael Benjamin
Michael Benjamin

Reputation: 371361

It's clear that width: 100% takes the width of the window, but not the document.

This behavior is not entirely clear in the spec as far as I can tell.

10.2 Content width: the width property

<percentage>

Specifies a percentage width. The percentage is calculated with respect to the width of the generated box's containing block. If the containing block's width depends on this element's width, then the resulting layout is undefined in CSS 2.1.


Two methods around the problem involve CSS positioning.

1. position: fixed

Fixed positioning makes the width relative to the viewport.

#title { 
  height: 50px;
  color: white;
  background-color: #404040;
  position: fixed; /* NEW */
  width: 100%; /* NEW */
}

DEMO

2. position: absolute

Absolute positioning also works:

#title {
  height: 50px;
  color: white;
  background-color: #404040;
  position: absolute;
  width: 100%; 
}

DEMO

Upvotes: 1

Related Questions