CSS 居中正方形 child 受其 parent 的宽度和高度限制(如 background-size:contain + center)

CSS centered square child limited by both width and height of its parent (like background-size:contain + center)

所以我见过很多制作正方形 div 的解决方案,但我还没有找到一个简单的解决方案,它的行为与 background-size:contain; background-position:center center;

完全一样

目标:

这种方法几乎是完美的,但它没有使正方形垂直居中:https://jsfiddle.net/8s4chau9/

#wrapper {
  width: 50%;
  height: 300px;
  border: 1px solid blue;
}
#square {
  aspect-ratio: 1/1;
  max-width: 100%;
  max-height: 100%;
  margin: auto;
  box-sizing: border-box;
  background-color: red;
}
<div id=wrapper>
    <div id=square></div>
</div>

我认为将包装器设为 flex 会起作用,但它不起作用:display:flex; align-items:center; justify-content:center;

希望有一天 none 当有人最终创建 css 单位 pw(parent 宽度)、ph(parent 高度)、pmin 时,这将是必要的和 pmax(类似于 vmin/vmax 但对于 parent 而不是视口)。

如果我没看错的话,你现在的问题是正方形没有垂直对齐。这可以通过翻译 CSS 函数轻松解决:

#wrapper {
  width: 50%;
  height: 300px;
  border: 1px solid blue;
}
#square {
  position: relative;
  top: 50%;
  aspect-ratio: 1/1;
  max-width: 100%;
  max-height: 100%;
  margin: auto;
  box-sizing: border-box;
  background-color: red;
  transform: translateY(-50%);
}
<div id=wrapper>
    <div id=square></div>
</div>

首先,你给你的方块分配一个位置而不是静态的,这样你就可以给它分配一个最高值。在这种情况下,我们希望它相对定位。

然后,您分配一个 top: 50%,将对其进行调整以提供 transform: translateY(-50%) 的居中结果。

这里有你编辑过的fiddle:https://jsfiddle.net/Bettylex/6ncks2fx/2/