Reputation: 40884
I have two div
elements; one of them with a scrollbar on the side:
+-------------+ ?
| div A | ?
+-------------+ ?
| |^|
| | |
| | |
| div B |=|
| | |
+-------------|v|
I want div A
to be exactly as wide as div B
minus the width of its scrollbar. The scrollbar is always there (by explicit overflow: scroll
). OTOH div A
is of fixed height and does not need scrolling. I want the client areas of div A
and div B
to be aligned.
I could probably make an artificial scrollbar control using JS. If possible, I'd prefer a CSS-based, native-looking solution, though.
I could put a separate piece of padding where the ?
on the picture are, if I somehow knew what the platform-dependent width of the scrollbar is.
Is there a way to achieve this, at least in modern browsers?
Upvotes: 8
Views: 9366
Reputation: 16821
Another possibility uses only css, and it is very reliable.
On the top div, create a inner div to hold the content, and a hidden pseudo :after
element to generate the scrollbar's width. I've used a display: table
aligment to keep inline, but other techniques will do as well:
Works like a charm: http://jsfiddle.net/4gu5mkzy/1/
#top {
width: 100%;
height: 100px;
display: table;
}
#top:after {
display: table-cell;
content: "";
overflow-y: scroll;
visibility: hidden;
}
.inner {
display: table-cell;
background: yellow;
}
<div id="top">
<div class="inner"><!-- content --></div>
</div>
Upvotes: 7
Reputation: 16821
You could create a Javascript simple function to calculate the width of the scrollbar. Just set a div width overflow: scroll
and an inner div, and subtract their offsetWidth
:
http://jsfiddle.net/mLjkr9ce/1/
HTML:
<div id='outer-div'>
<div id='inner-div'></div>
</div>
CSS:
#outer-div {
width:100%;
position: absolute;
overflow-y: scroll;
visibility: hidden;
}
JS:
var ow = document.getElementById("outer-div").offsetWidth;
var iw = document.getElementById("inner-div").offsetWidth;
alert(ow - iw); //Scrollbar's rendered width
Then set this value as the padding.
BUT
that may be pointless, since almost all (if not all) major browsers have a 17px width scrollbar:
See this article with the Test Results
Chrome v34 17 pixels
Internet Explorer v11 17 pixels
Internet Explorer v10 17 pixels
Firefox v29 17 pixels
Firefox v28 17 pixels
So basically, I believe a simple padding
of 17px might be enough, though the article states that is a common practice to use a 20px basis.
Upvotes: 1
Reputation: 105863
As far as i know, CSS alone will not do it unless you adapt you HTML and go for a little compromise.
Not a pixel perfect solution, but since scollbar are not alike from a browser to another ...
HTML test:
<div class="ab">A</div>
<div class="sc">
<div class="ab">B</div>
</div>
CSS test:
.ab {
width:200px;
background-color:gray;
}
.sc {
width:200px;
padding-right:1.1em;
height:100px;
overflow:auto;
}
.sc .ab {
height:200px;/*demo purpose */
}
Upvotes: 2