Sometimes you want to display some text that doesn't fit in it's boundaries, for example a one-line title at the top of the page, which might be too long to be displayed on a mobile device. Then you have to cut off the text and somehow show the user that what he sees is not actually the full text. Here I'll show you an elegant and simple way to achieve that with pure CSS. This is what the final result will look like:
For this to work, we need the following HTML:
<div class="text-container">
<div class="text">Your way too long text goes right in here</div>
<div class="overflow"></div>
</div>
There we have container wrapping the text element and an .overflow
element. That one will be the actual shadow above the text.
Next, we need to do some CSS setup on the container and the text itself. The container will get a fixed width in this example, just so that the text will actually be bigger than the container. To allow the overflow element to be positioned absolutely inside the container, the container needs to have a position
value other than static
itself. So if yours is already fixed
or absolute
, it's fine, otherwise, set it to relative
. We'll also set overflow: hidden
to hide any content that's bigger than the text box. Lastly, we'll set white-space: nowrap
to prevent the text from wrapping to the next line:
.text-container {
position: relative;
width: 100px;
}
.text-container .text {
white-space: nowrap;
overflow: hidden;
}
Now we get to our overflow element. It will be absolutely positioned, so that we can move it to the right, and it'll stretch the whole height of the container. Then we'll give it a fixed width of whatever width we want the shadow to be and lastly we'll apply a linear-gradient
as our actual shadow:
.text-container .overflow {
position: absolute;
top: 0;
right: 0;
bottom: 0;
width: 40px;
background: linear-gradient(to right, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 1) 100%);
}