You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为换行元素<br>之前的链接单独设置样式?

为换行元素<br>之前的链接设置样式的替代方案

下面是几种不用内联样式的实现方法:

方法1:使用CSS :has() 伪类(现代浏览器支持)

利用:has()伪类判断列表项里是否包含<br>,再排除掉<br>之后的链接,就能精准选中Link1和Link2:

li:has(br) a:not(br ~ a) {
  color: #ff4500;
  text-decoration: underline wavy;
}

原理:br ~ a会选中<br>之后的所有同级链接,not()排除这些元素,剩下的就是<br>之前的链接。

方法2:调整HTML结构(兼容性最好)

把<br>之前的内容包裹进一个容器,通过类名精准控制样式,这是兼容性最稳妥的方案:

<ul>
    <li>
        <span class="pre-br-section">
            <a href="#">Link 1</a> and <a href="#">Link 2</a>
        </span>
        <br>
        word word word word word word <a href="#">Link 3</a>
    </li>
</ul>

对应的CSS:

.pre-br-section a {
  color: #2e8b57;
  font-weight: bold;
}

方法3:先统一设置再反向覆盖

先给列表项里的所有链接设置样式,再把<br>之后的链接重置回默认样式:

li a {
  color: #1e90ff;
  text-decoration: none;
}

li br ~ a {
  color: inherit;
  text-decoration: underline;
}

这种方法不需要改变HTML结构,适合不能修改HTML的场景。

内容的提问来源于stack exchange,提问作者Wanderlust Consulting

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 17:22:38