Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position fixed element within fixed element relative to page

Tags:

html

css

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?

like image 434
joshfarrant Avatar asked Mar 14 '23 01:03

joshfarrant


1 Answers

#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 :)

like image 165
Gaurav Aggarwal Avatar answered May 04 '23 11:05

Gaurav Aggarwal