如何使CSS +操作符不忽略元素之间的明文?



我发布的一个流行的在线论坛没有能力在帖子中创建内联代码段。因此,我在Tampermonkey中创建了一个用户脚本,将代码块转换为内联代码块,除非它们紧跟着换行符<br>。到目前为止,我已经制作了一个Tampermonkey脚本,使用以下选择器将样式注入在线论坛的<head>:

br + code {
background-color: yellow;
}
<body>
<h2>Example A (this is correct)</h2>
<p>
This text is not yellow. <code>This code is not yellow.</code>
<br>
<code>But after a line break, the code is yellow!</code>
</p>
<h2>Example B (unwanted behaviour)</h2>
<p>
This text is not yellow. <code>This code is not yellow.</code>
<br>
After a line break, there is more text...
<code>...but the code is still yellow!</code>
</p>
<h2>Example C</h2>
<p>
This text is not yellow. <code>This code is not yellow.</code>
<br>
After a line break, there is more text and an empty span <span></span>...
<code>and that makes the code not yellow anymore!</code>
</p>
</body>

示例A工作得很好,只选择紧接在换行符之后的代码范围。然而,例子B有不需要的行为。

示例B的问题是在换行符<br>和内联代码跨度之间存在明文内容。看起来CSS选择器在换行符之后选择代码跨度,即使它们之间有纯文本内容,并将其设置为黄色,但我不希望这样。

示例C是解决此问题的HTML方法。我在<br><code>之间添加了一个空的<span>。这导致CSS样式不选择代码,决定代码不是第一个跟随<br>的元素。

但是我更喜欢css端来解决这个问题。如果有的话,是什么?

不幸的是,由于这个论坛对论坛帖子中允许的标签有严格的政策,任何替代方法都不起作用。我需要一个答案,实际上解决了提出的问题,我不能改变以任何方式提供的HTML,否则它很可能从我的论坛帖子被剥夺。以下是我尝试过的方法。在以下所有情况下,附加信息将被剥离:

  • 尝试将CSS类放在我想要样式的部分。
  • 试图将font-size以外的属性添加到文本部分。

空span解决方案(示例C)对我有效的唯一原因是论坛服务器允许您使用<span style="font-size: 12px">设置字体大小。如果我要完成现在的代码,我需要在内联代码span之前用this包围部分行。

这不是CSS问题,而是对<p><br>标记的语义和目的的误解。这是一篇很棒的关于语义及其重要性的文章。

TL:博士:在担心CSS之前,重构你的HTML使其语义正确,并适当使用CSS类,而不是用同级选择器使你的代码复杂化:

.highlighted {
background-color: yellow;
}
<p>Your first paragraph</p>
<p>A second paragraph without the linebreak</p>
<code class="highlighted">... code that is highlighted ...</code>
<p>A third paragraph</p>
<code>... this code isn't highlighted ...</code>

为什么不把所有需要改变背景的元素都放到

<div style="background-color: yellow;">
<br>
<p>
</div>

使用:nth-child()选择器,<code>...<code>可以从父元素继承其背景色,或者可以使用自定义背景色覆盖。例如,它可以在给定的HTML中实现如下:

br + code {
background-color: yellow;
}
h2:nth-child(3) + p code:nth-child(3) {
background-color: inherit;
}
<body>
<h2>Example A (this is correct)</h2>
<p>
This text is not yellow. <code>This code is not yellow.</code>
<br>
<code>But after a line break, the code is yellow!</code>
</p>
<h2>Example B (unwanted behaviour)</h2>
<p>
This text is not yellow. <code>This code is not yellow.</code>
<br>
After a line break, there is more text...
<code>...but the code is still yellow!</code>
</p>
<h2>Example C</h2>
<p>
This text is not yellow. <code>This code is not yellow.</code>
<br>
After a line break, there is more text and an empty span <span></span>...
<code>and that makes the code not yellow anymore!</code>
</p>
</body>

最新更新