I've got a fixed container which is vertically and horizontally centred on the page, and an element within that container. Ideally I would like to have this element positioned in the very top left of the window, however I'm struggling to make it work.
This JS Bin illustrates the problem.
https://jsbin.com/nodonatifo/edit?html,css,output
Initially I thought I would just be able to do something like this on the element.
#container {
width: 300px;
height: 400px;
background-color: #55ffdd;
/* Center on page */
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#element-actual {
background-color: red;
width: 100px;
height: 100px;
position: fixed;
top: 0px;
left: 0px;
}
<div id="container">
<div id="element-actual"></div>
</div>
However that just fixes the element in the top left corner of the parent container, rather than the window.
Is this possible with my current styles?
#container {
width: 300px;
height: 400px;
position: fixed;
top: 50%;
left: 50%;
background-color: #55ffdd;
margin-top: -200px;
margin-left: -150px;
}
If you use translate
property then its children div will place relatively to the parent div only even when it is position:fixed
so you can use the above code to place #container
in center and you red div will be placed relatively to the window not the parent div :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With