相对于 parent div 的百分比定位 div

Position a div in percentage relative to parent div

我正在尝试在 css 中创建一个场景,为此我正在使用 position: relativeposition:absolute。 我的问题是我正在尝试使用一些 css 属性将我的 child div 设置到我的 parent div 的中心,但它似乎没有上班。

这是我的做法:

.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;
}

这是它的作用

请注意,我的 div .game 也是另一个 div 的 child。如果您需要了解更多我的 html 或 css.

中发生的事情,请告诉我

使用 grid 将任何带有 place-content:center;

的内容居中

确保父元素有足够的高度使其子元素居中。

body {
    display: grid;
    min-height: 100vh;
    margin: 0;
}
.game {
    background-color: #5386e4;
    overflow: hidden;
    position: relative;
    width: 100%;
    height: 100%;
    display: grid;
    place-content: center;
}

.fish {
    height: 320px;
    width: 300px;
    background-color: #10121b;
}
<body>
    <div class="game">
        <div class="fish"></div>
    </div>
</body>

你可以使用 flex 来实现这个

.game {
  background-color: #5386e4;
  overflow: hidden;
  position: relative;
  height: 560;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.fish {
  height: 320px;
  width: 300px;
  background-color: #10121b;
}

制作“display”=>“flex”然后使用“justify-content”=>“center”&&“align-items”=>“center”将使子容器完美居中

最简单的方法是添加到 .fish div:

transform: translate(-50%, -50%);

您可以使用转换 属性:

.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;
    }

或者您也可以制作 parent div flex 并使用 flex-wrap: wrap; justify-content:center;align-items:center; 而无需制作 child absolute