17

CSS高级技巧:自动省略左侧文本

 3 years ago
source link: https://renfufei.blog.csdn.net/article/details/85159967
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

难以置信! 浏览器和CSS规范居然支持自动省略左侧的文本了。 通过 text-overflow: ellipsis, 搭配固定的 width 属性, 以及overflow: hidden 样式, 就可以实现这样的功能; 能用CSS实现,就不需要编写复杂的 JavaScript 代码来计算字符串宽度, 或者进行截断了. CSS的自动省略特性, 对无障碍环境也非常友好。

text-overflow: ellipsis 特性是很强大, 但其本身只能省略右侧文本;

如果想省略左边的文本怎么办呢?

这种需求还是很常见的: 比如, 有很多个文件路径, 其中有许多文件的目录是一模一样的, 这时候只显示最右侧的文本, 明显会比较合理。

下面介绍一个小技巧, 让自动省略出现在左边!

CSS样式

自动省略左侧文本, 和自动省略右侧文本的样式基本一致, 只是多了一点小技巧:

.ellipsize-left {
    /* 常规的CSS省略 */
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 200px;

    /* 让省略符显示在文本左侧 */
    direction: rtl;
    text-align: left;
}

我们需要指定text-align 样式, 并指定方向为RTL, 来自动裁剪左侧文本!

RTL, right to left, 从右到左;

LTR, left to right, 从左到右;

参考: https://developer.mozilla.org/en-US/docs/Web/CSS/direction

使用text-align和RTL来实现自动省略左侧文本的CSS特效, 是一个非常精巧的设计; 也许未来会很普及, 但现在这个技巧还很高端, 会的人不多!

在线Demo

在线Demo页面的地址为: https://davidwalsh.name/demo/css-left-ellipsis.php

从中可以看到,

相关的CSS代码如下:

<style type="text/css">
    .ellipsize-me {
        white-space: nowrap;
	/* 很显然,overflow的值不能是: visible */
        overflow: hidden;
        text-overflow: ellipsis;
        direction: rtl;
        text-align: left;
        width: 200px;
        border: 1px solid #999;
        padding: 10px;
    }
</style>

HTML代码如下:

<p class="ellipsize-me">
    first > second > third<br>
    second > third > fourth > fifth > sixth<br>
    fifth > sixth > seventh > eighth > ninth
</p>

显示效果类似这样:

first > second > third
...ourth > fifth > sixth
...nth > eighth > ninth

其中的省略符(...)是不可选择的。

效果截图:

#pic_center

这里其实也演示了CSDN博客新出的一个小功能, MarkDown编辑器中让图片居中。

只需要在图片路径后面, 加上hash #pic_center 即可。例如:

![](https://img-blog.csdnimg.cn/20181221115831570.png#pic_center)

你可以查看上面居中图片的URL。

原文链接: https://davidwalsh.name/css-ellipsis-left

Demo地址: https://davidwalsh.name/demo/css-left-ellipsis.php

翻译人员: 铁锚 - https://blog.csdn.net/renfufei

翻译日期: 2018年12月21日


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK