Matt Brunmeier Matt Brunmeier - 2 months ago 17
CSS Question

Getting a horizontal scroll bar within a 100% div

I'm trying to build a quick overview that shows the upcoming calendar week. I want it arranged horizontally so it can turn out to be quite wide if we show a full calendar week.

I've got it set up right now with an inner div with a fixed width (so that the floated "day" divs don't return below) and an outer div that's set to width: 100%. I'd LIKE for the outer div to scroll horizontally if the page is resized so that the inner div no longer fits in it, but instead the outer div is fixed larger at the width of the inner div and the page itself scrolls.

Gah I'm not good at explaining these things... Here's a bit of code that might clear it up..

The CSS:

.cal_scroller {
padding: 0;
overflow: auto;
width: 100%;
}

.cal_container {
width: 935px;
}

.day {
border: 1px solid #999;
width: 175px;
height: 200px;
margin: 10px;
float: left;
}


and the (simplified) structure:

<div class="cal_scroller">
<div class="cal_container">
<div class="day">Monday</div>
<div class="day">Tuesday</div>
<div class="day">Wednesday</div>
<div class="day">Thursday</div>
<div class="day">Friday</div>
</div>
</div>


So to try again - I'd like the
cal_scroller
div always be the page width, but if the browser is resized so that the
cal_container
doesn't fit anymore I want it to scroll WITHIN the container. I can make it all work if I set a fixed width on cal_scroller but that's obviously not the behavior I'm going for. I'd rather not use any javascript cheats to adjust the width of the div if I don't have to.

Answer

Your cal_scroller class is 100% + 20px (padding) wide. Use a margin on cal_container instead, like so:

.cal_scroller {
    padding: 10px 0;
    overflow: auto;
    width: 100%;
}

.cal_container {
    margin: 0 10px;
    width: 935px;
}

See here for a description of how the box model works (in short, the everything is outside the width/height of an element).

Also, block elements (like <div>s) are 100% width by default, making your 100% width declaration redundant.