Implementing Horizontal Scroll for Overflowing Text with Variable Widths
When text overflows a container, common solutions like ellipsis truncation may not be suitable, such as in navigation bars where hover interactions are needed. This guide explores techniques to create a smoooth horizontal scrolling effect for text that exceeds its container, acccommodating both fixed and variable container widths.
For hover-triggered scrolling, CSS animations can be applied to text elements. Start by ensuring the text does not wrap and is contained within a parent with hidden overflow:
<div class="container">
<span class="scroll-text">This is a long text that overflows the container width.</span>
</div>
.container {
width: 200px;
overflow: hidden;
}
.scroll-text {
white-space: nowrap;
}
To enable scrolling, convert the text element to inline-block to access its true width, allowing transformations:
.scroll-text {
display: inline-block;
white-space: nowrap;
}
For containers with fixed widths, calculate the scroll distance as the text width minus the container width. Use transform with calc() in a keyframe animation:
.scroll-text:hover {
animation: scroll-animation 2s infinite alternate linear;
}
@keyframes scroll-animation {
0% {
transform: translateX(0);
}
100% {
transform: translateX(calc(-100% + 200px));
}
}
In scenarios where the container width is variable, combine left (or margin-left) and transform properties to handle both element and container widths:
.scroll-text {
position: relative;
}
@keyframes scroll-animation {
0% {
left: 0;
transform: translateX(0);
}
100% {
left: 100%;
transform: translateX(-100%);
}
}
This approach ensures the text scrolls appropriately regardless of container or text width variations. Note that CSS alone cannot detect overflow to conditionally trigger animations; JavaScript may be required for such logic. Additionally, animasions might flicker when animating multiple opposing properties, which can be mitigated by optimizing timing functions or using hardware acceleration.