CSS Centering with Transform

让人想犯罪 __ 提交于 2019-11-27 14:44:34

问题


why does centering with transform translate and left 50% center perfectly (with position relative parent) but not right 50%?

Working example:

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

Example that doesn't center:

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

回答1:


Because translateX(-50%) moves something back to the left 50% (because of the - negative value), which means it pairs with left: 50%; to center something.

If you want to use right: 50%; then use that with translateX(50%) to center.

* {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>


来源:https://stackoverflow.com/questions/42121150/css-centering-with-transform

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!