我想使用 CSS 来定位一个元素,它是特定元素的“表亲”——换句话说,它们都是兄弟元素的后代。
我可以根据元素的“叔叔”或祖先的兄弟姐妹来定位元素,如下所示:
HTML:
<div>
<h2 data-section="name">Name</h2>
<p class="hint">Full name of the employee</p>
<p>
<span class="value1">Joe Tester</span>
</p>
</div>
<div>
<h2 data-section="details">Occupation</h2>
<p class="hint">Job role or title</p>
<p>
<span class="value1">Software Engineer</span>
</p>
</div>
CSS:
/*
* element that
* has a class of value1
* and is a descendent of a p
* that is next to an h2
* with attribute data-section=name
*/
h2[data-section="name"]~p .value1 {
color: #F92759;
}
结果:
但是如果data-section="name"
元素包裹在另一个元素中呢?是否仍然可以使以下 HTML 与上图相同?
<div>
<div>
<h2 data-section="name">Name</h2>
</div>
<p class="hint">Full name of the employee</p>
<p>
<span class="value2">Joe Tester</span>
</p>
</div>
实际应用body
:针对具有特定meta
元素的页面(内部标签)中的节点。
此处的示例 JSFiddle:http: //jsfiddle.net/nchaves/tefpY/