如果存在特定的CSS类组合,则更改另一个类的CSS

3
我还想将“three”的背景颜色更改为“lightblue”,但仅当页面上存在“one current”类组合时。注意:“three”不能获得其他类。我知道,您可以使用JavaScript来完成此操作,但是否也有本地CSS解决方案?
这是我的示例:

<!DOCTYPE html>
<html>
<head>
  <style> 
    .one.current {background-color: lightblue;}
  </style>
</head>
<body>
 <header>
  <p class="one current">The first paragraph.</p>
 </header>

 <main>
  <p class="two">The second paragraph.</p>
  <p class="three">The third paragraph.</p>
  <p class="four">The fourth paragraph.</p>
 </main>
</body>
</html>


你能将 one current 应用于它们的前任吗?在这种情况下,是 <body> 吗? - Ramon Balthazar
或者至少到header元素,这样.one.current + main > .three就可以工作了。 - Ilya Streltsyn
@IlyaStreltsyn,你能给我你的代码片段吗?它对我来说似乎不起作用... - bodemiller1
我把它发布为一个答案。 - Ilya Streltsyn
2个回答

2
在您的情况下,您可以在<header>中使用.one.current。 接下来,使用以下样式设置.three.one.current ~ main .three。 同时,使用以下样式设置标题中的<p>元素:.one.current p
关于~运算符的文档,请参考通用兄弟选择器(MDN)

是的,就是这样。如果“one current”在“header”中,而其余部分在“main”中,您是否也有解决方案? - bodemiller1
你为什么认为 .one.current ~ .three 会起作用? one.current 被包含在一个 <header> 中,该 <header> 本身是 .three 元素的兄弟元素;没有父选择器,这在 CSS 中(目前)是不可能的。 - David Thomas
在我的初始问题中,“header”和“main”都缺失了,所以Razär的答案是正确的。对于造成的混淆我感到抱歉。但是,确实没有父选择器你就无法解决它... - bodemiller1
@bodemiller1,只有在所选元素是兄弟元素时才能起作用。因此,<header>必须具有这些类,然后您可以使用.one.current p来设置<p>的样式。 - Ramon Balthazar

0
如果您可以为 header 元素设置类而不是其内部的 p 元素,可以使用以下选择器组合来定位同级元素中的段落:

<!DOCTYPE html>
<html>
<head>
  <style> 
    .one.current p {background-color: lightblue;}
    .one.current + main > .three {background-color: lightblue;}
  </style>
</head>
<body>
 <header class="one current">
  <p>The first paragraph.</p>
 </header>

 <main>
  <p class="two">The second paragraph.</p>
  <p class="three">The third paragraph.</p>
  <p class="four">The fourth paragraph.</p>
 </main>
</body>
</html>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接