After stumbling upon this solution years after it was originally posted, I realized that the accepted answer didn't quite work for me when dealing with different background colors. Experimenting with a dark grey background led to an unwanted dark box behind the text.
Determined to find a better solution, I came across this alternative method. Essentially, it involves having two identical instances of the text positioned on top of each other. The text's position is determined using css-grid's justify-content: start
, and an overflow:hidden
property set with a width of 0.
Upon hovering over the text, the width of the fill-text div expands, effectively revealing the overlay text from left to right. To prevent any jumping or wrapping of text during expansion, an additional div surrounds the overlay text, extending its width to accommodate the expanding div.
.wrapper {
position: relative;
width: 400px;
font-family: 'Arial', sans-serif;
font-size: 24px;
background: beige
}
.fill-wrapper {
width: 300px;
}
.fill-text {
display: grid;
justify-content: start;
position: absolute;
top: 0;
left: 0;
overflow: hidden;
word-break: keep-all;
width: 0;
color: red;
transition: 0.5s width ease-in-out;
}
.text {
width: 150px;
color: black;
}
.wrapper:hover .fill-text {
width: 150px;
transition: 0.5s width ease-in-out;
}
<div class="wrapper">
<div class="fill-text">
<div class="fill-wrapper">
My Text
</div>
</div>
<div class="text">
My Text
</div>
</div>