Stephen Stephen - 6 months ago 24
HTML Question

Fixed position inside relative container not working as expected?

I have a fixed div inside a relative container, however top and left on the fixed div don't seem to work as they should inside the relative container?

My understanding of fixed position is that it is relative to the window, not any container?

see example: fixed div inside relative container
https://jsfiddle.net/jfcb92mx/2/

<div class="relativecontainer">
<div class="fixedContainer">
This is experimental
</div>

<div class="otherContainer"></div>
</div>

.fixedContainer {
background-color:#ddd;
position: fixed;
padding: 2em;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.relativecontainer{
position: relative;
}

.otherContainer {
height:1000px;
background-color:#bbb;
}


example 2: fixed div without relative container
https://jsfiddle.net/LekhuleniB/0kmn7xrk/

<div class="fixedContainer">
This is experimental
</div>

<div class="otherContainer"></div>


.fixedContainer {
background-color:#ddd;
position: fixed;
padding: 2em;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}

.otherContainer {
height:1000px;
background-color:#bbb;
}


Am I missing something?

Answer

there is little mistake in your fiddle you wrote this

 <div class="relativecontainer"< 

instead of this

    <div class="relativecontainer"> 

try it by correcting it then give relative position to relative container it will work fine

Comments