increase width on overflow to adjust scrollbars

css, html

Solution

The content width of an element includes the width of scrollbar, and as far as I know, you cannot fight this behavior.

Suppose you are trying to create a shrink-wrap div that contains two 250px wide columns. The browser calculate its width as 500px, then the height, and if a scrollbar is required, it fits the scrollbar inside those 500px reducing the available width to 483px (or so).

A tricky solution is as follows:

- Add sufficient amount of right padding on the box that (could) display scrollbar

- Set `width` property on that box or make that box shrink-wrap around its contents

- Set `max-height` to desired value and `overflow-y` property to `auto` to trigger automatic scrollbar

At this point the box will be as wide as desired and the scrollbar, if visible, draws over the right padding; not interfering with the width.

In order to display the chrome (border and padding) you need to create additional divs.

- `Demo` http://jsfiddle.net/salman/KZLmW/show/

- `Code` http://jsfiddle.net/salman/KZLmW/

HTML Markup:

<div id="ListBorder">
    <div id="ListOverflow">
        <div id="ListHolder">
            <ul id="LeftList">
                <li></li><li></li><li></li>
            </ul>
            <ul id="RightList">
                <li></li><li></li><li></li>
            </ul>
        </div>
    </div>
</div>

CSS (only the important bits)

#ListHolder ul {
    float: left;
    width: 250px;
}
#ListHolder {
    width: 500px;
    overflow: hidden;
}
#ListOverflow {
    width: 500px;
    overflow: auto;
    max-height: 350px;
    padding-right: 20px;
}
#ListBorder {
    width: 500px;
    border: 1px solid;
    padding: 20px;
}

Note:

- `#ListHolder` is used for clear-fix

- `#ListBorder` can be used to add a border and padding to match the desired output

Problem

What should be my CSS to make a div adjust its width when scrollbar is visible. Here is the scenario, I have a div and child elements ``` <div id="ListHolder"> <ul id="LeftList"> <li></li> <li></li> <li></li> </ul> <ul id="RightList"> <li></li> <li></li> <li></li> </ul> </div> ``` I want to adjust my div width automatically for scrollbars when it has overflow. Means when there is no scrollbar it should be like image on left side and when scrollbars becomes visible it should automatically adjust width for scrollbars. I do not want to use javascript but with pure CSS and HTML. And I believe it is possible with CSS and HTML only. Considering above UL Lists, my CSS is something like ``` #ListHolder { display:inline-block; } #ListHolder > ul { width:250px; //<---Necessary to keep fixed width not percentage display:inline-block; } #ListHolder > ul > li { display:inline-block; } #LeftList { float:left; } #RightList { float:right; } ```

Original source