George Mauer
George Mauer

Reputation: 122052

CSS - position element over another inside a scrolling area

I have the following html structure

<div id="scrolling-container">
    <div id="cover"></div>
    <div id="contents">
        A variable amount of iframes
    </div>
</div>

Here is the base jsbin explaining the issue.

I would like to be able to side-scroll #contents but I want it to be covered entirely by a transparent element (#cover) that I can use for click-detection and to allow easier side-scrolling on a tablet.

It should be possible to do this with css alone. #cover { position:absolute,top:0,bottom:0,left:0,right:0} seems like it would be the way to go here as that's a technique I've used dozens of times before, but with scrolling it does not stretch all the way to the right, but rather just to the tip of the initially visible scrolling area. As you scroll, it no longer covers the elements

Here is a demonstration of the issue. Try scrolling the container and you'll see the problem.

Upvotes: 1

Views: 3456

Answers (4)

apaul
apaul

Reputation: 16170

Update

You could

You should

You can still, totally drop that and use jQuery,

Example

js

$(document).ready(function () {
    var x = $('#contents').width();
    $('#cover').width(x);
});

$(window).resize(function () {
    var x = $('#contents').width();
    $('#cover').width(x);
});

$('#scrolling-container').scroll(function () {
    var x = $('#contents').width();
    $('#cover').width(x);
});

css

div {
  border: 1px solid grey;
}

#scrolling-container {
  overflow-x: scroll;
  position: relative;
}
#contents {
  width: 4000em;
  height: 10em;
}

#cover {
  position: absolute;
  z-index: 100;
  top:0;
  bottom:0;
  background-color: blue;

}

Sorry about that, this should work as advertised.

Upvotes: 1

A.M.K
A.M.K

Reputation: 16795

Try setting the contents of the div to position: relative and then using a psuedo element to generate the cover:

Demo: http://jsbin.com/arajag/1/edit

CSS:

div {
  border: 1px solid grey;
}

#scrolling-container {
  overflow-x: scroll;
  position: relative;
}
#contents {
  width: 400em;
  height: 10em;
  position: relative;
}

#contents:after {
  content: " ";
  position: absolute;
  z-index: 100;
  background-color: blue;
  top: 0;
  left: 0;
  bottom: 0;
  width: 100%;
}

HTML: Remove #cover

I know that there is a gap above and below the cover, that's because Chrome sets a margin before and after the contents. You should adjust for this anyway so I don't think it'll be an issue.

Upvotes: 2

twinkle
twinkle

Reputation: 1

Try this..

#cover { 
  width: 400em;
  height: 20em;
  position: absolute;
  z-index: 100;
  background-color: blue;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}

Is this what you meant??

Upvotes: -1

Goran Lepur
Goran Lepur

Reputation: 594

Here you go http://jsbin.com/oquguh/1/edit , i made your #container div the one who handles scrolling.

Upvotes: 0

Related Questions