pimvdb pimvdb - 3 months ago 17
CSS Question

Use full width excluding overflow scrollbar with "position: absolute"

I would like to have a small red div with full width at a fixed top position, inside another div that has

overflow: scroll
. I hope the jsFiddle makes it clear: http://jsfiddle.net/mCYLm/2/.

The issue is that the red div is overlapping the scrollbar. I guess
right: 0
means the right hand side of
; it does not subtract the scrollbar of
. When I move the
overflow: scroll
, then the red banner has the right size (fiddle). However, it is not at a fixed position anymore (scrolling down makes the banner scroll up).

How can I achieve the following two things together?

  • The red banner is at the fixed position like in this fiddle.

  • The red banner has full width except the scrollbar like in this fiddle.

I'd like to get this working in Google Chrome.


<div class="wrapper">
<div class="red-banner"></div>
<div class="main">
<div class="item">foo</div>
<div class="item">foo</div>
<div class="item">foo</div>
<div class="item">foo</div>


div.wrapper {
position: relative;

div.main {
height: 200px;
overflow-y: scroll;

div.item {
border: 1px solid black;
margin: 20px;
padding: 20px;

div.red-banner {
background-color: red;
position: absolute;
left: 0;
top: 0;
right: 0;
height: 20px;


Seems like this isn't possible with pure CSS, so here's a JavaScript (jQuery) hack:

$(function() {
  var $container = $("<div>").css({ height: 1, overflow: "scroll" }).appendTo("body");
  var $child = $("<div>").css({ height: 2 }).appendTo($container);
  window.SCROLLBAR_WIDTH = $container.width() - $child.width();