An easy solution that doesn't involve resorting to JavaScript and will not break CSS transforms is to simply have a non-scrolling element, the same size as your scrolling element, absolute-positioned over it.
The basic HTML structure would be
CSS
<style>
.parent-to-position-by {
position: relative;
top: 40px; /* just to show it's relative positioned */
}
.scrolling-contents {
display: inline-block;
width: 100%;
height: 200px;
line-height: 20px;
white-space: nowrap;
background-color: #CCC;
overflow: scroll;
}
.fixed-elements {
display: inline-block;
position: absolute;
top: 0;
left: 0;
}
.fixed {
position: absolute; /* effectively fixed */
top: 20px;
left: 20px;
background-color: #F00;
width: 200px;
height: 20px;
}
</style>
HTML
<div class="parent-to-position-by">
<div class="fixed-elements">
<div class="fixed">
I am "fixed positioned"
</div>
</div>
<div class="scrolling-contents">
Lots of contents which may be scrolled.
</div>
</div>
parent-to-position-by
would be the relative div
to position something fixed with respect to.scrolling-contents
would span the size of this div
and contain its main contentsfixed-elements
is just an absolute-positioned div
spanning the same space over top of the scrolling-contents
div
.div
with the fixed
class, it achieves the same effect as if it were fixed-positioned with respect to the parent div
. (or the scrolling contents, as they span that full space)