早上好。你好,
我希望用两种颜色的线条为标题加下划线。例如半蓝,半黑。
我想它是由CSS完成的,但我还没弄明白该怎么做。
有没有人有解决方案?
谢谢大家,节日快乐。
答案 0 :(得分:3)
您可以为该行的每一半使用: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>
&#13;
如果您有多行标题,则可以将文本拆分为两个跨度,然后使用text-decoration
。
h1 {
max-width: 400px;
}
h1 span:first-child {
text-decoration: red underline;
}
h1 span:last-child {
text-decoration: green underline;
}
&#13;
<h1><span>Lorem ipsum dolor </span><span>sit amet, consectetur.</span></h1>
&#13;
您可以使用一些j来创建更动态的解决方案。
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)
&#13;