Emma N
Emma N

Reputation: 13

How to make an absolutely positioned element sit outside the scrolling parent but still scroll with it?

I have a scrolling div of small preview images which the user should be able to hover over and see a full size image. I've achieved this by using position: absolute; on the larger images.

This works fine for the first line of previews, but when I scroll down to view the second line, the full size image appears further down the page - where the previews had been before I scrolled to them.

However, if I set the parent to be position: relative; the images are only visible inside the scrolling div - so the user can only see a section of each image at a time and must scroll to see the whole thing.

HTML:

<div class="container">
    <div class="preview">
        <img class="big">
        <img class="small">
    </div>
</div>

But with multiple preview divs inside the container div.

CSS:

.container {
    width: 300px;
    height: 120px;
    overflow: auto;
 }
.preview {
    display: inline-block;
}
.small {
    width: 100px;
}
.big {
    display: none;
    position: absolute;
    z-index: 2;
}
.preview:hover .big {
    display: block;
}

I've got a fiddle here, using coloured divs instead of images to represent .big and .small : https://jsfiddle.net/jsd8t3gr/3/

Is there anyway I can keep the .big images floating outside the .container div like it does in the first fiddle example (no relative positioning), but also have them move when the container div scrolls, like they do in the second fiddle example (with relative positioning on the .container div)?

Everything I've found so far is related to stopping the images from overflowing the parent, I've not found anything about making that happen on purpose.

EDIT - Using this method without setting container div to have relative position works perfectly in Firefox; it's just a case of getting this to work cross-browser

Upvotes: 1

Views: 203

Answers (1)

Hugo Silva
Hugo Silva

Reputation: 6948

Without relative position, define top of big so it will be relative to the root. If you don't define top, it will be relative to the parent by default. Which doesn't seem to update on Chrome when you scroll. Nice find!

Working fiddle - https://jsfiddle.net/jsd8t3gr/6/

Upvotes: 1

Related Questions