9

我有一个具有子元素的元素和具有相同子元素的另一个元素,但还有一个文本节点:

<p><strong>This should be heading</strong></p>
...
<p>There is a sentence that has <strong>strong text</strong> inside it.</p>

我无法以任何方式修改 DOM 结构,包括没有 JavaScript。我所能做的就是编辑 CSS,但我想将内联的样式设置为与唯一的孩子strong不同的样式。strong

我认为这可能有效:

p strong:only-child
{
    color: red;
}

但是,这两个项目都变成了红色

有没有办法只使用 CSS 来定位没有文本节点兄弟的子节点?

我不认为它可以做到,但我想我会问,以防有某种聪明的解决方法。

4

2 回答 2

4

根据我的理解,我认为它应该是

p:first-child
{
    color: red;
}

JSFiddle

于 2013-08-01T13:06:20.027 回答
0

以下代码无法正常工作。

p strong:only-child{
    color: red;
}

当你有这样的代码时:

<p><strong>This should be heading</strong></p>
...
<p>There is a sentence that has <strong>strong text</strong> inside it.</p>

在每种情况下,“strong”元素都是其父元素“p”的唯一子元素。因此,这里的两个“强”元素都将匹配。这就是为什么你的两个项目都变成了红色。

要仅更改第一段的颜色,您可以编写(正如有人之前提到的):

p:first-child{
    color:red;
  }

或其等价物,即:

p:nth-child(1){
}

我知道在这里不适用的最好情况是通过添加 'class="red"' 来更改 html 代码,如下例所示:

版本 1:

HTML

<p><strong class="red">This should be a heading</strong></p>
<p>This is a sentence with <strong>strong text</strong> in it.</p>

CSS

.red{
  color:red;
}

版本 2:

<p class="red"><strong>This should be a heading</strong></p>
<p>This is a sentence with <strong>strong text</strong> in it.</p>

CSS

.red{
  color:red;
}
于 2018-01-14T03:36:09.970 回答