Reputation: 9293
I want a sidebar to exclude from any scroling behaviour on page - so it is position:fixed
.
But I want it to be inside wrap
as a parent container and right:0
from wrap
and not from window.
How to do this ?
.wrap{width:250px; margin:0 auto; height:100vh;background:silver;}
.sidebar{position:fixed;top:0;right:0;height:100vh;background:gold;}
<div class='wrap'>
<div class='sidebar'>sidebar</div>
</div>
Upvotes: 4
Views: 45
Reputation: 272899
One idea is to not define right
and tell the browser to use the static position. For this you need to make sure the static position is on the right.
Here is an example where you have to adjust the direction (and reset it for the content)
.wrap {
width: 250px;
margin: 0 auto;
height: 150vh;
background: silver;
direction:rtl;
}
.sidebar {
position: fixed;
top: 0;
height: 100vh;
background: gold;
}
.wrap > div:last-child {
direction:ltr;
}
body {
margin:0;
}
<div class='wrap'>
<div class='sidebar'>sidebar</div>
<div> some content</div>
</div>
From the specification:
For the purposes of this section and the next, the term "static position" (of an element) refers, roughly, to the position an element would have had in the normal flow.
Then
If all three of 'left', 'width', and 'right' are 'auto': First set any 'auto' values for 'margin-left' and 'margin-right' to 0. Then, if the 'direction' property of the element establishing the static-position containing block is 'ltr' set 'left' to the static position and apply rule number three below; otherwise, set 'right' to the static position and apply rule number one below.
Here is another idea with position:sticky
.wrap {
width: 250px;
margin: 0 auto;
height: 150vh;
background: silver;
}
.sidebar {
position: sticky;
float:right; /* Yes float!*/
top: 0;
height: 100vh;
background: gold;
}
body {
margin:0;
}
<div class='wrap'>
<div class='sidebar'>sidebar</div>
<div> some content</div>
</div>
Upvotes: 4