In this short tutorial, I will show you my new favorite technique which fades overflowing text gracefully into the background.
The Idea
By setting amax-width
value, overflow:hidden
and an :after
pseudo element, we can achieve the effect that you can see in the demo. Here is what each of these will help us with:- The element will increase its width freely, until it hits the value set by
max-width.
- At that point, all excess text will be hidden thanks to the
overflow:hidden
property. - To prevent the text from breaking to a new line, we use
white-space:nowrap.
- To create a smooth transition between the text and the background color of the element, we will use an
:after
pseudo element. This element will have alinear-gradient
that goes from transparent to the color of the background. This element is positioned to the right of the container, and becomes visible only when the element expands.
text-overflow:ellipsis
as more of the text is actually shown, and it blends nicely with the
design of the page. However it comes at the cost that it takes more
lines of CSS, and you have to manually set the maximum width. In some
cases, the extra effort is worth it when the goal is a cleaner design.The Code
To set the stage, we should first write a few lines of HTML:index.html
<input type="text" value="This text will expand" />
<h2><span id="elem" class="overflow-300"></span> and this will shift to the side.</h2>
The text input is only needed in order to give the visitor the
ability to change the content easily, otherwise they would have to use
their browser’s developer tools. The element which has the overflow
technique applied, is the #elem span. I have given it a class called overflow-300, which we will use to implement the technique in our CSS.assets/css/styles.css
h2 span{
font-weight:bold;
display:inline-block;
vertical-align: top;
}
A thing to keep in mind, is that we can not set a width
or max-width
on an element which is set to display:inline
(the default display of span elements). This necessitates that we give it a display of inline-block
. And here is the technique itself:.overflow-300{
overflow:hidden;
max-width:300px;
position:relative;
white-space: nowrap;
}
.overflow-300:after{
content:'';
position: absolute;
left:300px;
margin-left: -40px;
width: 40px;
height:100%;
top:0;
background:linear-gradient(to right, rgba(240, 244, 245, 0), rgba(240, 244, 245, 1));
}
If you were to change the max width of the element, you would also need to change the left value of the :after
element.Lastly, we have some jQuery that will listen for the text input event on the textbox, and update the contents of the span:
assets/js/script.js
$(function(){
var elem = $('#elem'),
textbox = $('input[type=text]');
textbox.on('input', function(){
elem.text(textbox.val());
});
textbox.trigger('input');
});
With this, our sweet text overflow technique is ready! Do you have suggestions or other handy techniques? Share them in the comment section.
0 komentar:
Post a Comment