我有一些这样的HTML。
<div class="platform-content">
<div class="content-wrapper">
<section class="entry">
<article class="post-type-page id123 page type-page status-private hentry" id="id123">
<section class="entry-header">
<h2 class="entry-title">Heading Text</h2>
</section>
我只需要定位一个 h2 元素才能使用 css 更改其颜色。我尝试执行以下操作。
#id123 h2 {
color: red;
}
它可以工作,除了页面上的每个 h2 都变为红色。我也不能直接针对 h2,因为它也会影响其他页面。我无法弄清楚如何仅针对该页面上的一个特定 h2,而不是页面上的每个 h2。
在页面的下方,我有一些表单字段,其中有这样的 h2 元素。我不希望这些变成红色。
<li id='field_18_75' class='gfield gsection field_sublabel_below field_description_below gfield_visibility_visible'>
<h2 class='gsection_title'>Title Text</h2>
</li>
问题是,所有这些html都是生成的,我对此没有任何控制权。因此,例如,我无法向元素添加自定义 ID。
你应该只能捕获带有nth-child(n(的元素
#id123 section h2:nth-child(1) {
color: orange;
}
<div class="content-wrapper">
<section class="entry">
<article class="post-type-page id123 page type-page status-private hentry" id="id123">
<section class="entry-header">
<h2 class="entry-title">Heading Text</h2><h2 class="entry-title">Heading Text</h2>
</section>
</article>
</section>
</div>
由于您在<h2>
元素上指定了id
,因此您指定的代码应该可以工作。请记住,每个页面上的 id 应该是唯一的,因此 CSS 指令#id123 h2 { color: red; }
应该只影响<h2 id="id123"></h2>
元素。
例:
h2 {
color: blue;
}
#id123 h2 {
color: red;
}
<div class="platform-content">
<div class="content-wrapper">
<section class="entry">
<article class="post-type-page id123 page type-page status-private hentry" id="id123">
<section class="entry-header">
<h2 class="entry-title">Heading Text</h2>
</section>
</article
</section>
</div>
</div>
<div class="platform-content">
<div class="content-wrapper">
<section class="entry">
<article class="post-type-page id123 page type-page status-private hentry" id="id124">
<section class="entry-header">
<h2 class="entry-title">Heading Text</h2>
</section>
</article
</section>
</div>
</div>
如果您希望特定标签为红色,请为其指定唯一 ID,然后将其颜色设置为红色。
#uniqueId {
color : red
}
<h2 id = "uniqueId">Heading Text</h2>
为该特定h2
元素提供 id:
<h2 class="entry-title" id="my-id">Heading Text</h2>
然后在 CSS 中:
#my-id {
color: red;
}
<h2 id="idA" class="entry-title">Heading Text</h2>
将特定 id 放在 h2 标签上。
#idA{
color : red
}
使用 :nth-child 来实现此目的。像这样检查我的答案..
.entry-header h2:nth-child(1){
color:red;
}
.entry-header h2:nth-child(2){
color:blue
}
.entry-header h2:nth-child(3){
color:yellow
}
<div class="platform-content">
<div class="content-wrapper">
<section class="entry">
<article class="post-type-page id123 page type-page status-private hentry" id="id123">
<section class="entry-header">
<h2 class="entry-title">Heading Text1</h2>
<h2 class="entry-title">Heading Text2</h2>
<h2 class="entry-title">Heading Text3</h2>
<h2 class="entry-title">Heading Text4</h2>
</section>
David Angulo - 如果条目标题是唯一的,那么您可以使用 #id123 h2.entry-title 代替。