作为WEB开发者, 我们开发的网站内容要尽可能的适应各种长度的文字. 你要尽可能的保证你的网站能让5个长度的文字与50个长度的文字显示效果相同. 过去, 这只能通过提前裁剪文字或者使用JavaScript来实现, 但如今我们可以只通过CSS来达到目的, 只需使用如max-width
与text-overflow.
在这篇教程里, 我将向你展示我最喜爱的隐藏溢出文字的处理技巧.
The Code
index.html
1
|
<h2>
<span
id
=
"elem"
class
=
"overflow-300"这是一个很长很长的标题
</span>
and this will shift to the side.
</h2>
|
style.css
1
2
3
4
5
|
h2 span
{
font-weight
:
bold
;
display
:
inline-block
;
vertical-align
:
top
;
}
|
这里需要值得注意的是, 我们不能给display:inline
(span标签的默认显示)的元素设置width
或者max-width
. 所以我们必须修改显示为inline-block
. 接下来得代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
.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
)
)
;
}
|
你如果想修改元素的最大宽度, 你就必须修改:after
元素里的位置left
信息.