Html 变换:翻译(-50%,-50%)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46184458/
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
Transform: translate(-50%, -50%)
提问by Theodore Steiner
When working with hero images or full screen anything, I typically see text or images with the following bit of css:
在处理英雄图像或全屏任何内容时,我通常会看到带有以下 css 位的文本或图像:
.item {
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Can someone explain to me what this code is actually doing?
有人可以向我解释这段代码实际上在做什么吗?
回答by Terry
The reason why transform: translate(-50%, -50%)
is required is because you want the center of the elementto line up with the center of its parent. In simple terms, it can be boiled down to translateX(-50%) translateY(-50%)
, which means:
之所以transform: translate(-50%, -50%)
需要,是因为您希望元素的中心与其父元素的中心对齐。简单来说,它可以归结为translateX(-50%) translateY(-50%)
,这意味着:
- move me leftwards by 50% of my width, along the x-axis, and
- move me upwards by 50% of my height, along the y-axis
- 沿 x 轴将我向左移动宽度的 50%,然后
- 沿 y 轴将我向上移动高度的 50%
This effectively moves the center of the element to its original top left corner. Remember than when you set left: 50%; top 50%
on the element, you are moving its top left corner to the center of its parent (which means it is not visually centered at all). By moving the element back leftwards and upwards by half of its width and height respectively, you sure that its center now aligns with the parent's center, making it visually horizontally + vertically centered.
这有效地将元素的中心移动到其原始的左上角。请记住,当您left: 50%; top 50%
在元素上设置时,您将其左上角移动到其父项的中心(这意味着它根本没有在视觉上居中)。通过将元素分别向左和向上移动其宽度和高度的一半,您可以确保它的中心现在与父级的中心对齐,使其在视觉上水平+垂直居中。
As a proof-of-concept, see the code snippet below: hover over the parent to cause the child element's "ghost" to reposition itself by means of transform: translate(-50%, -50%)
:
作为概念验证,请参阅下面的代码片段:将鼠标悬停在父元素上,使子元素的“幽灵”通过以下方式重新定位transform: translate(-50%, -50%)
:
body {
margin: 0;
padding: p;
}
.parent {
background-color: #ccc;
width: 100vw;
height: 100vh;
position: relative;
}
.child {
background-color: rgba(0,0,255,0.5);
width: 50px;
height: 50px;
position: absolute;
top: 50%;
left: 50%;
}
.child::before {
background-color: rgba(255, 0, 0, 0.5);
position: absolute;
top: 0;
left: 0;
width: 50px;
height: 50px;
content: '';
transition: all .5s ease-in-out;
}
body:hover .child::before {
transform: translate(-50%, -50%);
}
<div class="parent">
<div class="child"></div>
</div>