我只想选择一个 id,当它跟随一个特定的类时。
像 .class + #id { css }
这样的东西行得通吗?还是有其他方法可以做到这一点?
只有当它们遵循 .single_job_listing
时,我才尝试选择 #jp-relatedposts
最佳答案
选择器 +
将起作用。它只会选择 ID 指示为 #jp-relatedposts
的 div,前提是它位于类 .single_job_listing
的元素之后。
举个例子:
HTML
<div id="main" class="site-main">
<div class="single_job_listing">
Your job listing
</div>
<div id="jp-relatedposts" class="jp-relatedposts">
Related Posts
</div>
<div id="jp-non-relatedposts" class="jp-relatedposts">
Non-related Posts
</div>
</div>
CSS
.single_job_listing + #jp-relatedposts, .single_job_listing + #jp-non-relatedposts {
background-color: cyan;
}
.jp-relatedposts {
background-color: #ccc;
}
只有 #jp-relatedposts
会被 cyan 规则选中,而 #jp-non-relatedposts
将具有默认值背景颜色。
您可以从 here 阅读更多关于兄弟选择器的信息
关于css - 选择与类相邻的 css id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45520115/