Rama Rao M Rama Rao M - 5 months ago 28
Javascript Question

Sticky div inside fixed positioned div

Need to place a

div
which should be sticky on scrolling of parent
div
which is positioned to
fixed
. Please check the below code snippet.

<style>
.outer{
width:300px;
height:400px;
border:1px solid red;
overflow:auto;
position:fixed;
top:50px;
left:100px;
}
.tag{
position:absolute;
top:0px;
left:80px;
background:#ffcc33;
border:2px solid #dfa800;
border-top:0px;
padding:3px 5px;
}
.inner{
height:800px;
border:1px solid green;
margin:0px 5px;
}
</style>

<div class="outer"> <!-- This is scroll-able-->
<div class="tag">Click here to Refresh</div><!-- This should be sticky-->
<div class="inner"><!--This content causes scrolling-->
Inner content...........
</div>
</div>


So here,
tag
part should be stuck to top of the
outer
div.Here is the fiddle

Is there any workaround to achieve this with pure css.

Answer

Try introducing a wrapper div around the tag - this way you can separate the positioning logic on the wrapper, and set the tag to position: fixed; for stickiness. Note that position: fixed; by itself on the tag will pull it out of its normal dom flow, so you need to adjust its positioning.

HTML

<div class="tag-wrapper">
    <div class="tag">Click here to Refresh</div>
</div>

CSS

.tag-wrapper {
    position: absolute;
    top: 0px;
    left: 80px;
}

.tag {
    position: fixed;
    background: #ffcc33;
    border: 2px solid #dfa800;
    border-top: 0px;
    padding: 3px 5px;
}

click to see fiddle