问题描述
我最近重构了一些CSS,并惊喜地发现了一种更简单的方法来水平对齐绝对定位的元素:
I recently refactored some of my CSS and was pleasantly surprised to find an easier way to horizontally align my absolutely positioned element:
.prompt-panel {
left: 50%;
transform: translateX(-50%);
}
这很好用!即使我的元素的宽度是自动的.但是,我不知道如何使它真正起作用.我的假设是,translateX只是一种现代的,性能更高的移动元素的方式,但事实并非如此.
This works great! Even if my element's width is auto. However, I do not understand what's going on to make this actually work. My assumption was that translateX was just a modern, more performant means of moving an element around, but that does not appear to be the case.
这两个值不应该互相抵消吗?而且,为什么
Shouldn't these two values cancel each other out? Furthermore, why does
.prompt-panel {
left: -50%;
transform: translateX(50%);
}
与第一个代码段显示的结果不同吗?
not show the same result as the first code snippet?
推荐答案
CSS left
属性基于父元素的大小. transform
属性基于目标元素的大小.
The CSS left
property is based on the size of the parent element. The transform
property is based on the size of the target element.
百分比:指[应用样式的元素的]边框的大小
Percentages: refer to the size of bounding box [of the element to which the style is applied]
http://www.w3.org/TR/css3-transforms/#transform-property
百分比:是指包含块的高度
Percentages: refer to height of containing block
http://www.w3.org/TR/CSS2/visuren.html#position -道具
如果父级宽度为1000px,子级宽度为100px,浏览器会将您的问题中的规则解释为:
If the parent is 1000px wide and the child is 100px, The browser would interpret the rules in your question as:
示例1:
.prompt-panel {
left: 500px;
transform: translateX(-50px);
}
示例2:
.prompt-panel {
left: -500px;
transform: translateX(50px);
}
这篇关于为什么“离开:50%,变换:translateX(-50%)"?将元素水平居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!