css transform translate 在 y 轴上不起作用

css transform translate doesn't work on y axis

我想在 x 轴和 y 轴上集中一个 div 块。但我无法使用 translate.

移动方块

.maincontain {
  position: relative;
  min-height: 100%;
  width: 100%;
  float: left;
}

.bannerimage {
  position: absolute;
  width: 64%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-size: 100% 100%;
  border-radius: 5px;
  background-color: violet;
}
<div class="maincontain">
  <div class="bannerimage" id="image_gallery">
    <img src="./img/2.jpg" alt="2">
    <img src="./img/3.jpg" alt="3">
    <img src="./img/4.jpg" alt="4">
  </div>
</div>

您可以考虑使用 flexgrid 来避免玩弄 positionmin-height 也可以使用 vh 单位(视口高度)代替需要从父级继承高度值才能计算的百分比。

示例:

body {
  margin: 0;
}

.maincontain {
  display: grid;
  min-height: 100vh;
}

.bannerimage {
  margin: auto;
  width: 64%;
  border-radius: 5px;
  background-color: violet;
}
<div class="maincontain">
  <div class="bannerimage" id="image_gallery">
    <img src="./img/2.jpg" alt="2">
    <img src="./img/3.jpg" alt="3">
    <img src="./img/4.jpg" alt="4">
  </div>
</div>

body {
  margin: 0;
}

.maincontain {
  display: flex;
  min-height: 100vh;
}

.bannerimage {
  margin: auto;
  width: 64%;
  border-radius: 5px;
  background-color: violet;
}
<div class="maincontain">
  <div class="bannerimage" id="image_gallery">
    <img src="./img/2.jpg" alt="2">
    <img src="./img/3.jpg" alt="3">
    <img src="./img/4.jpg" alt="4">
  </div>
</div>