【问题标题】:CSS Centering with TransformCSS 居中与变换
【发布时间】:2017-06-26 13:04:33
【问题描述】:

为什么使用变换居中平移和左 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%);
 }

【问题讨论】:

    标签: css centering


    【解决方案1】:

    因为translateX(-50%) 将某物移回 50%(因为- 为负值),这意味着它与left: 50%; 配对以使某物居中。

    如果您想使用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>

    【讨论】:

    • 也取决于direction rtl 或 ltr
    • @Banzay 随时留下您自己的答案,阐明direction 在此类定位中的作用。使用leftright 时,文档的direction 是什么无关紧要,因为您指定的是rightleft codepen.io/anon/pen/PWdrBG
    • 那更多的是问题,而不是注释。谢谢 :)
    【解决方案2】:

    据我了解,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%)),我们将使对象居中。

    【讨论】:

      猜你喜欢
      • 2012-10-14
      • 1970-01-01
      • 1970-01-01
      • 2018-05-17
      • 2014-12-20
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      • 2016-10-28
      相关资源
      最近更新 更多