使用变换的 CSS 居中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42121150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CSS Centering with Transform
提问by norkuy
why does centering with transform translate and left 50% center perfectly (with position relative parent) but not right 50%?
为什么使用变换居中平移并完美地将 50% 居中(与位置相对父)而不是右 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%);
}
回答by Michael Coker
Because translateX(-50%)
moves something back to the left50% (because of the -
negative value), which means it pairs with left: 50%;
to center something.
因为translateX(-50%)
将某些东西向左移动50%(因为-
负值),这意味着它与left: 50%;
某些东西成对地居中。
If you want to use right: 50%;
then use that with translateX(50%)
to center.
如果你想使用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>