gpt4 book ai didi

html - 仅当指定的兄弟存在时,如何更改 html 元素的 css 样式?

转载 作者:行者123 更新时间:2023-11-28 00:55:21 24 4
gpt4 key购买 nike

我浏览了 MDN CSS 文档,但没有看到任何可以选择我想要设置样式的元素的组合器。

/* second-span red when first-span is present */
[first-span] ~ [second-span] {
color: red;
}

/* first-span blue ONLY when second-span is present */
/* HOW TO ? */
[first-span] /* combinator doesn't exist */ {
color: blue;
}
<p>
<span first-span="">I am #1</span><br>
<span second-span="">I am #2</span>
</p>

<p>
<span first-span="">I am #1</span>
<!-- no second span -->
</p>

<p>
<span second-span="">I am #2</span>
</p>

仅当在下面的 sibling 中找到另一个指定的 sibling 时,我才尝试将样式应用于元素。

在代码片段中,如果在以上 sibling 中找到选择表达式中的左手,则第一个 CSS 语句用于设置元素样式。但似乎没有组合器产生相反的效果。

我该怎么做?

最佳答案

通过合并nth-child与其他伪类一起,它使您能够从具有特定长度的元素集中指定元素。

使用 <br> 会稍微复杂一些标记,作为 <p> 的子元素,但是,这仍然可以满足您的需求:

/* this will color the first element of three children nested in a p tag blue */
p span:nth-child(1):nth-last-child(3){
color: blue;
}

/* this will color the third element of three children nested in a p tag red */
p span:nth-child(3):nth-last-child(1) {
color: red;
}
<p>
<span first-span="">I am #1</span><br>
<span second-span="">I am #2</span>
</p>

<p>
<span first-span="">I am #1</span>
<!-- no second span -->
</p>

<p>
<span second-span="">I am #2</span>
</p>

这针对三个元素中的第一个,然后是三个元素中的最后一个。

关于html - 仅当指定的兄弟存在时,如何更改 html 元素的 css 样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45220964/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com