-1

I am wondering how i can center absolute element inside container, but without changing position of childs elements inside centered element. *Child elements are absolute too.

I simply want to center the '#ground' both, vertically and horizontally inside container, without moving any child inside '#ground', is it do-able?

#container {
  display: grid;
  width: 150px;
  height: 150px;
  background: black;
}

#ground {
  position: absolute;
  width: 100px;
  height: 100px;
  background: red;
}

.tile {
  position: absolute;
  width: 30px;
  height: 30px;
  background: aqua;
  top: 20px;
  left: 50px;
}
<div id="container">
  <div id="ground">
    <div class="tile"></div>
  </div>
</div>
Hiurako
  • 177
  • 2
  • 10

3 Answers3

1

Simply.
No as far as my knowledge goes

But, you can center #ground and then move it's content to the original position again with absolute positioning

#container {
  display: grid;
  width: 150px;
  height: 150px;
  background: black;
  position: relative;
}

#ground {
  position: absolute;
  width: 100px;
  height: 100px;
  background: red;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.tile {
  position: absolute;
  width: 30px;
  height: 30px;
  background: aqua;
  top: 5px;
  left: 25px;
}
<div id="container">
  <div id="ground">
    <div class="tile"></div>
  </div>
</div>
ciekals11
  • 2,032
  • 1
  • 10
  • 24
  • I was able to get similar result, but what i am looking for is that i need the tile to be in exact same position within '#ground' while '#ground' is centered. : / – Hiurako May 12 '20 at 14:08
0

Using absolute positions is not the best way to align the elements. You can use flexbox which is a better way and is responsive too!

#container {
  display: flex;
  width: 150px;
  height: 150px;
  background: black;
  align-items: center;
  justify-content: center;
}

#ground {
  width: 100px;
  height: 100px;
  background: red;
}

.tile {
  position: relative;
  width: 30px;
  height: 30px;
  background: aqua;
  top: 20px;
  left: 50px;
}
<div id="container">
  <div id="ground">
    <div class="tile"></div>
  </div>
</div>
Satnam Singh
  • 324
  • 2
  • 12
-2

You should use

#ground {
left:(no. of pixels);
top:(no. of pixels);
}

Or you can also use margin and set it as auto.