Transition centered text to left / right edges without overflowing

戏子无情 提交于 2019-12-22 12:42:17

问题


I was able to transition text-align from center to left. With this code, if you run it, then hover over, you'll see the top one goes to the left. However the bottom overflows on the right; how can I figure out how to make the transition to right not overflow?

Note: This is a demo of my real application, which has strings/elements of unknown/variable width, from 1 to anything to fill a single line (no wrapping).

.header {
  position: fixed;
  width: 70%;
  background-color: springgreen;
}
.title {
  text-align: center;
}
.menu {
  text-align: center;
}
.trans-left {
  transition: margin-right 1s;
}
.trans-right {
  transition: margin-left 1s;
}
.header:hover .trans-left {
  margin-right: 100%;
}
.header:hover .trans-right {
  margin-left: 100%;
}
<body>
  <div class='header'>
    <div class='title'>
      <span class='trans-left'>This one goes left</span>
    </div>
    <div class='menu'>
      <span class='trans-right'>This one goes right</span>
    </div>
  </div>
</body>

回答1:


You're aligning the text elements like this:

margin-left: 100%;
margin-right: 100%;

This positions each element – from the starting point of the box – to the left and right edges.

Hence, the left edge of the left-moving box will align with the left edge of the container.

And the left edge of the right-moving box will align with the right edge of the container. This causes the rest of this box to overflow.

Try this instead:

margin-right: 90%; /* adjust as needed */

Edit based on revised question

Here is an alternative solution that works regardless of content width.

.header {
  position: fixed;
  width: 70%;
  background-color: springgreen;
}
.title, .menu {
  text-align: center;
  position: relative;
  width: 100%;
  height: 50px;
}
.trans-left {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  transition: 1s;
}
.trans-right {
  position: absolute;
  right: 50%;
  transform: translateX(50%);
  transition: 1s;
}
.header:hover .trans-left {
  left: 0;
  transform: translateX(0);
  transition: 1s;
}
.header:hover .trans-right {
  right: 0;
  transform: translateX(0);
  transition: 1s;
}
<div class="header">
  <div class="title">
    <span class="trans-left">This one goes left</span>
  </div>
  <div class="menu">
    <span class="trans-right">This one goes right</span>
  </div>
</div>

More details: Element will not stay centered, especially when re-sizing screen



来源:https://stackoverflow.com/questions/38622227/transition-centered-text-to-left-right-edges-without-overflowing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!