CSS 以变换为中心

CSS Centering with Transform

为什么使用转换平移和左 50% 完美居中(相对父位置)居中而不是右 50%?

工作示例:

span[class^="icon"] {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
 }

不居中的例子:

span[class^="icon"] {
  position: absolute;
  top: 50%;
  right: 50%;
  transform: translate(-50%, -50%);
 }

因为translateX(-50%)将某物向左移 50%(因为-负值),这意味着它与[=14配对=] 使某物居中。

如果你想使用 right: 50%; 然后使用 translateX(50%) 居中。

* {margin:0;}
span {
  position: absolute;
  top: 50%; right: 50%;
  transform: translate(50%,-50%);
  background: black;
  color: white;
}

body:after, body:before {
  content: '';
  position: absolute;
  background: red;
}

body:after {
  top: 50%;
  left: 0; right: 0;
  height: 1px;
}
body:before {
  left: 50%;
  top: 0; bottom: 0;
  width: 1px;
}
<span>center me</span>

据我理解,top:left:其实是指how far the object's top edge is from the top of its container(容器是指相对位置最近的父元素)和how far the object's left edge is from the left of its container。具体来说,top: 50% 表示对象移动容器高度的 50%,left: 50% 表示对象移动容器宽度的 50%。

一旦元素的原点位于中心,您可以看到通过将元素向左移动其宽度的一半并向上移动其高度的一半,对象的中心将位于原点而不是它的左上角。

如果我们改为 right: 50%,则元素的右侧将从容器的右侧移动容器宽度的 50%,这意味着它的 upper-right edge 处于打开状态起源。因此,通过将其向右移动其宽度的 50% 并向上移动其高度的 50% (transform(50%, -50%)),我们将使对象居中。