首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >用两种颜色的单行加下划线的文本

用两种颜色的单行加下划线的文本
EN

Stack Overflow用户
提问于 2017-12-30 15:20:02
回答 1查看 274关注 0票数 0

早上好。你好,

我希望用两种颜色的线条给标题加下划线。比如,半蓝半黑。

我想这是由CSS完成的,但我还没有想好怎么做。

有谁有解决方案吗?

谢谢大家,节日快乐。

EN

回答 1

Stack Overflow用户

发布于 2017-12-30 15:28:21

您可以对该行的每一半使用:before:after伪元素。如果你想增加行高,你还需要增加相同数量的:after伪元素的负边距。Demo

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
h1 {
  display: inline-flex;
  flex-direction: column;
}
h1:after, 
h1:before {
  content: '';
  border-bottom: 1px solid green;
  order: 2;
  width: 50%;
}
h1:after {
  margin-left: auto;
  margin-top: -1px;
  border-color: red;
}
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<h1>Lorem ipsum dolor sit.</h1>

如果您有多行标题,那么您可以将文本拆分为两个跨度,并使用text-decoration代替。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
h1 {
  max-width: 400px;
}
h1 span:first-child {
  text-decoration: red underline;
}
h1 span:last-child {
  text-decoration: green underline;
}
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<h1><span>Lorem ipsum dolor </span><span>sit amet, consectetur.</span></h1>

您可以使用一些js来创建更动态的解决方案。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class Title {
  constructor(text, parts = []) {
    this.text = text;
    this.parts = parts;
    return this.create()
  }

  checkLength() {
    let l = this.parts.reduce((r, e) => r + e.width, 0);
    if (l > 100) {
      throw new Error('Sum of all parts width must be under 100%')
    }
  }

  create() {
    this.checkLength();
    let title = this.createTitle();
    this.addLines(title);
    return title;
  }

  createTitle() {
    let h1 = document.createElement('h1');
    h1.textContent = this.text;
    h1.style.display = 'inline-block';
    h1.style.position = 'relative';
    return h1;
  }

  createLine(input) {
    let {color,width} = input;
    let line = document.createElement('span');
    line.style.position = 'absolute';
    line.style.bottom = 0;
    line.style.border = '1px solid ' + color;
    line.style.width = width + '%';
    return line;
  }

  addLines(title) {
    let that = this;
    this.parts.forEach(function(part) {
      let line = that.createLine(part);
      line.style.left = this.prev + '%';
      this.prev += part.width;
      title.appendChild(line)
    }, {prev: 0})
  }
}


let title = new Title('Random Title', [
  {color: 'red', width: 60},
  {color: 'blue', width: 20},
  {color: 'green', width: 20}
])

let title2 = new Title('Lorem ipsum dolor.', [
  {color: 'black', width: 80},
  {color: 'green', width: 20}
])


document.body.appendChild(title)
document.body.innerHTML += '<br>'
document.body.appendChild(title2)

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48035211

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文