Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Position a div in percentage relative to parent div

I’m trying to create a scene in css and for that I am using position: relative and position:absolute.
My problem is that I’m trying to set my child div to the center of my parent div using some css properties and it doesn’t seem to work.

Here’s what I do :

.game {
  background-color: #5386e4;
  overflow: hidden;
  position: relative;
}

.fish {
  height: 320px;
  width: 300px;
  position: absolute;
  transform-origin: center; // Here I am trying to set the origin of the div in its center.
  top: 50%;  // And here I am trying to center vertically the child div in the parent div.
  left: 50%; // Same here but horizontally
  z-index: 10000;
  background-color: #10121b;
}

Here’s what it does

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Note that my div .game is also child of another div. Let me know if you need to see more of what is going on in my html or css.

>Solution :

You can use transform property:

.fish {
      height: 320px;
      width: 300px;
      position: absolute;
      transform-origin: center; // Here I am trying to set the origin of the div in its center.
      top: 50%;  // And here I am trying to center vertically the child div in the parent div.
      left: 50%; // Same here but horizontally
      transform: translate(-50%, -50%);
      z-index: 10000;
      background-color: #10121b;
    }

Or you can also make your parent div flex and use flex-wrap: wrap; justify-content:center; and align-items:center; without making child absolute

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading