Search code examples
htmlcsscss-positiongame-physics

how to make a div stay in a div


I'm making a pong clone using HTML/CSS/Js. I've set a div element to act as a border for the game, just to keep things in a confined space. How do I get elements (for example, a scoreboard) to act relative to their parent element? For example, if I tell the child to move 50% left, it moves to the center of the parent-div, and NOT to the center of the web-page. Basically I want the child confined by the dimensions of their parent (haha). It seems like

child-div {
   position:relative;
}

in CSS would do the trick, but it's not...maybe it's because I'm developing in CodeAcademy's IDE?


Solution

  • position:relative means relative to itself not parents/children etc. It seems likely that you want relative on the parent and possibly absolute on the children. Without code, it's hard to help much further

    Here's a quick demo for you.

    .container {
      width: 80%;
      height: 250px;
      margin: 0 auto;
      position: relative;
      border: 4px solid green;
    }
    .scoreboard {
      width: 200px;
      height: 50px;
      background: lightblue;
      border: 2px solid grey;
      position: absolute;
      top: 10px;
      /* just for a bit of space */
      left: 50%;
      /*almost centered*/
      margin-left: -100px;
      /* half of known width */
    }
    <div class="container">
      <div class="scoreboard"></div>
    </div>

    Note...there are other centering methods for absolutely positioned divs depending on whether the width is known and browser support requirements

    left: 50%; does not center an element...it moves the element's top/left corner to the center of the containing element. You have to move it back half of it's width (if known)...see above.

    One final point....positioned elements are not constrained to their ancestor elements but rather positioned in relation to them. It's quite common to have positioned elements outside the bounds of parents.