How To Center A Fixed Div Inside Another Div?
Solution 1:
The trick is to set position:fixed
on the sidebar (with left:0
and right:0
respectively) and then add margin-left:23%
to #wrapper
:
#wrapper {
width: 54%;
margin-left: 23%;
background: #0FF;
}
.sidebar {
width: 23%;
position: fixed;
left:0; top: 0;
}
#wrapper + .sidebar { /* target second sidebar */left: inherit; /* reset left */right:0;
}
if you want the green sidebars to stay in place, but the red boxes to move away, then something like this should work:
.sidebar {
width: 23%;
float: left;
position: relative; /* so sub-containers are relative to sidebar */
}
.sidebar.contents {
margin: auto;
background: #F00;
min-width: 100px;
width: 100%; /* relative to sidebar */height: 100px;
}
.sidebar.contents.fixed {
background: #0F0;
position: fixed; /* starts a new context... */width: 23%; /* so this is not relative to sidebar *.
}
Solution 2:
Not possible with just CSS. When you make an element fixed
, it removes it from its "context" and makes its new "context" the document. That's why specifying width: 100%
on the position: fixed
element spans the page.
Edit: I'm assuming that you want the green sidebars to stay in place but the red boxes to move away as you scroll (I'm making this assumption because of the way you've named your classes on your page).
Solution 3:
you need to fix the sidebar
, not its contents.
Just remove the float
and set the position fixed to top and right
.sidebar {
width: 30%;
position: fixed;
top:0;
right:0;
}
Post a Comment for "How To Center A Fixed Div Inside Another Div?"