【问题标题】:Text underlined by a single line of two colors由两种颜色的单行下划线的文本
【发布时间】:2017-12-30 15:20:02
【问题描述】:

早上好。你好,

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

我想它是由 CSS 完成的,但我还没有弄清楚该怎么做。

有人有解决办法吗?

谢谢大家,节日快乐。

【问题讨论】:

  • 欢迎来到 Stack Overflow!预计您至少会尝试自己编写代码。 Stack Overflow 不是代码编写服务。我建议你做一些additional research,通过谷歌或搜索SO,尝试一下。如果您仍然遇到问题,请返回您的代码并解释您尝试过的操作。

标签: css


【解决方案1】:

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

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;
}
<h1>Lorem ipsum dolor sit.</h1>

如果您有多行标题,那么您可以将文本分成两个跨度并改用text-decoration

h1 {
  max-width: 400px;
}
h1 span:first-child {
  text-decoration: red underline;
}
h1 span:last-child {
  text-decoration: green underline;
}
<h1><span>Lorem ipsum dolor </span><span>sit amet, consectetur.</span></h1>

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

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)

【讨论】:

  • 非常感谢您的帮助。我要去试试你的代码。非常好的一天结束,
  • 谢谢它有效。行长适应文本的长度。如果我希望线条具有定义的宽度,我该怎么办?我将把它应用到 Wordpress 网站侧边栏中的小部件标题。
  • 在这种情况下,您可以在伪元素上定义宽度,也可以在 :after 你需要设置 margin-left 等于伪元素之前的宽度 jsfiddle.net/Lg0wyt9u/2671
  • 这是一张图片,向您展示我拥有什么以及我想做什么。 imageshack.com/a/img924/4708/911oDH.jpg
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-09
  • 2016-09-30
  • 1970-01-01
  • 2012-09-30
  • 2018-10-17
  • 2021-10-03
  • 2019-03-04
相关资源
最近更新 更多