Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

html - Transform: translate(-50%, -50%)

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...