Apply CSS except for child with specific ID 除了具有特定ID的子元素之外应用CSS

huangapple go评论74阅读模式
英文:

Apply CSS except for child with specific ID

问题

考虑以下标记:

<ul>
 <li class="search-results">
   <p>请给我样式</p>
   <span id="not-me-please">请不要给我样式</span>
 </li>

和CSS:

 ul li.search-results {color:green}

显然,段落和 span 都会有绿色文本,但有没有办法使用 :not 选择器来确保 span 不会获得样式?

英文:

Consider the following mark up:

&lt;ul&gt;
 &lt;li class=&quot;search-results&quot;&gt;
   &lt;p&gt;Style me please&lt;/p&gt;
   &lt;span id=&quot;not-me-please&quot;&gt;Do not style me&lt;/span&gt;
 &lt;/li&gt;

</ul>

And the CSS:

 ul li.search-results {color:green}

Obviously both the paragraph and the span will have green text but is there a way to use the :not selector so that the span doesn't get the styling?

答案1

得分: 1

You can use the :not pseudo-class and exclude the #not-me-please element as below, but I would not recommend this approach as it can be considered bad practice.

<ul>
  <li class="search-results">
    <p>Style me please</p>
    <span id="not-me-please">Do not style me</span>
  </li>
</ul>
ul li.search-results > *:not(#not-me-please) {color:green}

Recommendation:

Either add a specific class to the elements intended to be green (i.e., <p class="search-results_label">) or target the p tags directly (i.e., ul li.search-results > p).

Note that I would not advise targeting the global ul tag directly either.

英文:

You can use the :not pseudo-class and exclude the #not-me-please element as below, but I would not recommend this approach as it can be considered bad practice.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

&lt;ul&gt;
 &lt;li class=&quot;search-results&quot;&gt;
   &lt;p&gt;Style me please&lt;/p&gt;
   &lt;span id=&quot;not-me-please&quot;&gt;Do not style me&lt;/span&gt;
 &lt;/li&gt;
&lt;/ul&gt;

<!-- language: lang-css -->

 ul li.search-results &gt; *:not(#not-me-please) {color:green}

<!-- end snippet -->

Recommendation

Either add a specific class to the elements intended to be green (i.e., &lt;p class=&quot;search-results_label&quot;&gt;) or target the p tags directly (i.e., ul li.search-results &gt; p).

> Note that I would not advise targeting the global ul tag directly either.

huangapple
  • 本文由 发表于 2023年4月17日 19:07:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76034494.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定