Noitidart Noitidart - 4 months ago 8
CSS Question

Transition centered text to left / right edges without overflowing

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
, can you please help me to 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>




Answer

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

Comments