项目中的文字下划线实现方案

83 阅读2分钟

闲言

时隔2年重新划水写写文章,23年6月在公司躲过了2次人员优化的我,在第三次主动领取大礼包。在家gap三个月(跑过滴滴、接过兼职),到新公司一系列经历感到身心极其emo,整个人都很抑郁(从公司离职到新环境的适应、公司福利待遇落差、家庭琐事等等)在这里想要感谢我现在的leader,给我的一些建议和帮助,让我慢慢走出那段差劲的状态。

  • 给大家一些对我有帮助的方法:
    1. 上下班路上听书看书
    1. 制定可以接受的运动计划(10个俯卧撑、500个跳绳等等)
    1. 坚持写文章

说来惭愧之前都没怎么看书

创建项目 创建项目

好啦废话不多说,下面记录一些开发app中webview的H5页面遇到的一些问题,今天给大家带来的是文字下划线的四种实现方法

文字下划线

1. css自带属性

  • 通过css属性text-decoration自带下划线
  • text-decoration 属性规定添加到文本的修饰,下划线、上划线、删除线等。

缺点:无法自定义下划线样式


.demo {
  /*关键值*/
  text-decoration: none;                     /*没有文本装饰*/
  text-decoration: underline red;            /*红色下划线*/
  text-decoration: underline wavy red;       /*红色波浪形下划线*/

  /*全局值*/
  text-decoration: inherit;
  text-decoration: initial;
  text-decoration: unset;
}
.textDecoration {
  width: 150px;
  text-decoration: underline;
  text-decoration-line: underline;
  text-decoration-color: #ffe3d6; /* 红色 */
  text-decoration-style: dashed; /* 虚线 */
}

2. border

  • CSS border 属性用于指定元素边框的样式、宽度和颜色。

缺点:不能跟随文本换行

.textBorder {
  width: 150px;
  border-bottom: 1px solid #ffe3d6;
}

3. 伪类

  • 通过给dom添加 before/after 添加下划线

缺点:效果同border一样不能跟随文本换行


.textAfter {
  position: relative;
  width: 150px;
}
.textAfter::after {
  content: '';
  position: absolute;
  width: 100%;
  height: 1px;
  bottom: 0;
  left: 0;
  background: #ffe3d6;
}

4. 背景(项目中使用)

  • 通过使用 background: linear-gradient 可以解决文本换行跟随,自定义下划线高度问题
.textBody {
    width: 150px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    word-break: break-all;
}
.text {
  background: linear-gradient(180deg, rgba(255, 227, 214, 0) 66.6%, #ffe3d6 66.6%);
}

实际效果

code.juejin.cn/pen/7376109…