变换:翻译(-50%,-50%) [英] Transform: translate(-50%, -50%)

查看:17
本文介绍了变换:翻译(-50%,-50%)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在处理英雄图像或全屏任何内容时,我通常会看到带有以下 css 的文本或图像:

.item {顶部:50%;左:50%;变换:翻译(-50%,-50%);}

有人可以向我解释一下这段代码实际上在做什么吗?

解决方案

需要transform: translate(-50%, -50%)的原因是因为你想要中心元素的 对齐其父元素的中心.简单来说,可以归结为translateX(-50%) translateY(-50%),意思是:

  • 沿 x 轴将我向左移动宽度的 50%,然后
  • 沿 y 轴将我向上移动 50% 的高度

这有效地将元素的中心移动到其原始的左上角.记住当你设置 left: 50%;元素的顶部 50%,您将其左上角移动到其父元素的中心(这意味着它根本不在视觉上居中).通过将元素分别向左和向上移动其宽度和高度的一半,您可以确保它的中心现在与父级的中心对齐,使其在视觉上水平+垂直居中.

作为概念证明,请参阅下面的代码片段:将鼠标悬停在父元素上,通过 transform: translate(-50%, -50%) 使子元素的幽灵"重新定位自身:

body {边距:0;填充:p;}.父母{背景颜色:#ccc;宽度:100vw;高度:100vh;位置:相对;}.孩子 {背景颜色:RGBA(0,0,255,0.5);宽度:50px;高度:50px;位置:绝对;顶部:50%;左:50%;}.child::before {背景颜色:rgba(255, 0, 0, 0.5);位置:绝对;顶部:0;左:0;宽度:50px;高度:50px;内容: '';过渡:所有 .5 秒的缓入缓出;}身体:悬停 .child::before {变换:翻译(-50%,-50%);}

<div class="child"></div>

When working with hero images or full screen anything, I typically see text or images with the following bit of css:

.item {
 top: 50%;
 left: 50%;
 transform: translate(-50%, -50%);
}

Can someone explain to me what this code is actually doing?

解决方案

The reason why transform: translate(-50%, -50%) is required is because you want the center of the element to line up with the center of its parent. In simple terms, it can be boiled down to translateX(-50%) translateY(-50%), which means:

  • 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

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.

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%):

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>

这篇关于变换:翻译(-50%,-50%)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆