CSS居中与变换 [英] CSS Centering with Transform
本文介绍了CSS居中与变换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么以transform为中心进行平移,而将50%的中心居中完美地定位(相对于父级的位置)却不正确地将50%居中?
why does centering with transform translate and left 50% center perfectly (with position relative parent) but not right 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%)
将某些内容移回了 left 50%(因为-
为负值),这意味着它与left: 50%;
配对以使内容居中.
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.
如果要使用right: 50%;
,请与translateX(50%)
一起使用以居中.
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>
这篇关于CSS居中与变换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文