如何将 div 容器移动到屏幕中央,让子 divs 集中在其中

How to move div container in the center of the screen, with children divs centralized inside of it

我有以下 HTML/CSS 代码:

<style>.dummy {
  color: greenyellow;
}

.middle-container {
  position: absolute;
  top: 50%;
  left: 50%;
}

.middle-container-box {
  width: 50px;
  height: 50px;
  background-color: red;
}

.middle-container-text {
  color: red;
  font-weight: bold;
  font-size: 15px;
}

</style>
<html>

<body>
  <div class="dummy">
    Lorem Ipsum is simply dummy text...
  </div>
  <div class="middle-container">
    <div class="middle-container-box"></div>
    <div class="middle-container-text">
      this text needs to be in the center
    </div>
  </div>
</body>

</html>

在此沙盒中:https://codesandbox.io/s/2py075pqnr 我需要 middle-container 位于屏幕中央,div 和文本元素(位于此容器内)集中在容器内。

所以它应该向左移动,如:https://prnt.sc/n349h1(我们只需要向左移动)。但是用固定值(以像素为单位)移动它不是一个选项,因为我需要它在所有屏幕分辨率上工作。

您需要使用 translate 将方框移回中心并弯曲以使其子项居中:

.dummy {
  color: greenyellow;
}

.middle-container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform:translate(-50%, -50%); /* this moves this box back to the middle (back up and left 50% of itself) */
  display:flex;           /* the following four align it's children to the center horizontally and vertically */
  flex-direction:column;
  align-items:center; 
  justify-content:center;
}

.middle-container-box {
  width: 50px;
  height: 50px;
  background-color: red;
}

.middle-container-text {
  color: red;
  font-weight: bold;
  font-size: 15px;
}
<div class="dummy">
  Lorem Ipsum is simply dummy text...
</div>
<div class="middle-container">
  <div class="middle-container-box"></div>
  <div class="middle-container-text">
    this text needs to be in the center
  </div>
</div>

更改.middle-container,将顶部、左侧、右侧、底部设置为0,然后将边距设置为自动。你的文字已经在中心,因为它给了 div 它的宽度,你需要做的是将 .middle-container-box 放在中间设置显示以阻止和保证金为 0 自动。见下文:

.middle-container {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}
.middle-container-box {
    width: 50px;
    height: 50px;
    background-color: red;
    display: block;
    margin: 0 auto;
}
.middle-container-text {
    color: red;
    font-weight: bold;
    font-size: 15px;
    text-align: center;
}

你可以用 transfom

CSS

.dummy {
  color: greenyellow;
}

.middle-container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

.middle-container-box {
  width: 50px;
  height: 50px;
  background-color: red;
  display: inline-block;
}

.middle-container-text {
  color: red;
  font-weight: bold;
  font-size: 15px;
}

DEMO HERE