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

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

问题描述

在使用英雄图像或全屏显示时,通常会看到带有以下CSS的文本或图像:

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?

推荐答案

需要transform: translate(-50%, -50%)的原因是,您希望元素的 center 与其父级的中心对齐.简单来说,它可以简化为translateX(-50%) translateY(-50%),这意味着:

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:

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

这有效地将元素的中心移动到其原始的左上角.请记住,而不是在元素上设置left: 50%; top 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.

作为概念验证,请参见下面的代码片段:将鼠标悬停在父元素上,以使子元素的"ghost"通过transform: translate(-50%, -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%):

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天全站免登陆