Recently, I encountered a situation where I needed a button with text initially aligned to the right but then smoothly transitioning to the center upon hover or focus.
After exploring various solutions, I devised the following approach. Many of the existing answers focused on animating the "position", which can be inefficient. In my implementation, I chose to utilize only the "transform" property for a more optimized performance. Although the markup might seem excessive for such a simple task, it proved to be effective in achieving the desired outcome.
body {margin: 0}
ul, li {
margin: 0;
padding: 0;
}
li {
width: 30%;
padding: 10px 0;
}
button {
width: 100%;
height: 50px;
margin: 0;
}
.center-line {
position: absolute;
width: 2px;
height: 100%;
background: lightgray;
left: 15%;
top: 0;
}
.outer {
text-align: right;
transition: 200ms transform;
}
.inner {
display: inline-block;
transition: 200ms transform;
}
button:hover .outer {
transform: translateX(-50%);
}
button:hover .inner {
transform: translateX(50%);
}
<ul>
<li>
<button>
<div class="outer">
<div class="inner">Text 1</div>
</div>
</button>
</li>
<li>
<button>
<div class="outer">
<div class="inner">Text Two</div>
</div>
</button>
</li>
<li>
<button>
<div class="outer">
<div class="inner">Text Longer Three</div>
</div>
</button>
</li>
</ul>
<span class="center-line" />