karlosos
karlosos

Reputation: 1174

Fixed div related to another div

I want to create a fixed element which will be in the same position while scrolling down and up, but also will be relative in x-axis to a different div while resizing the window.

#blackbox {
  width: 500px;
  height: 2000px;
  background-color: black;
  color: white;
  margin: 0 auto;
}

#floater {
  width: 150px;
  background-color: blue;
  color: white;
  position: fixed;
  top: 50px;
  right: 120px;
  /* want here 10px on right from black box */
}
<html>
  <div id="blackbox">
    This is blackbox
    <br> This is blackbox
    <br> This is blackbox
    <br> This is blackbox
    <br> This is blackbox
    <br>
  </div>
  <div id="floater">
    Always 10px from black box
  </div>

</html>

Perfect scenario when resolution is same as mine: when window is big

When screen resolution is smaller: when window is small

Whem screem resolution is bigger: enter image description here

Edit: I've found the solution here.

#floater {
    left: calc(50% + 510px); /* 50% + blackbox width + wanted 10px space *.
}

Upvotes: 1

Views: 57

Answers (2)

Mauricio Moraes
Mauricio Moraes

Reputation: 7373

One way is using a wrapper div with display: table; and another two inside it with display: table-cell;.

Those "table-cells" will stay side by side, then you can put whatever you want inside them.

Take a look:

#wrapper {
  display: table;
}
#blackbox {
  width: 500px;
  height: 2000px;
  background-color: black;
  color: white;
  margin: 0 auto;
  display: table-cell;
}
#floater-wrapper {
  display: table-cell;
}

#floater {
  width: 150px;
  height: 40px;
  background-color: blue;
  color: white;
  margin-left: 10px;
  margin-top: 50px;
}
<html>
<div id='wrapper'>
  <div id="blackbox">
    This is blackbox
    <br>This is blackbox
    <br>This is blackbox
    <br>This is blackbox
    <br>This is blackbox
    <br>
  </div>
  <div id="floater-wrapper">
    <div id="floater">
      Always 10px from black box
    </div>
  </div>
</div>

</html>

Upvotes: 1

Jay
Jay

Reputation: 395

try this

#blackbox {
  width: 500px;
  height: 2000px;
  background-color: black;
  color: white;
  margin: 0 auto;
}

#floater {
  width: 150px;
  background-color: blue;
  color: white;
  position: fixed;
  top: 50px;
  left: 50%;
  /* want here 10px on right from black box */
}
<html>
  <div id="blackbox">
    This is blackbox
    <br> This is blackbox
    <br> This is blackbox
    <br> This is blackbox
    <br> This is blackbox
    <br>
  </div>
  <div id="floater">
    Always 10px from black box
  </div>

</html>

Upvotes: 0

Related Questions