简体   繁体   English

如何定位除特定容器内的所有h2标签外的所有标签

[英]How do I target all h2 tags except those within a certain container

I have an article that contains a gallery, but I do not want the styling for the article's h2 tags to affect h2's inside the gallery. 我有一篇包含画廊的文章,但我不希望文章的h2标签的样式影响画廊内的h2。 I have tried using the :not() pseudo class, but it seems I can't use this for this problem. 我已经尝试过使用:not()伪类,但是看来我不能用它解决这个问题。

I want to know if it's possible without overriding the article h2 styling. 我想知道是否有可能不覆盖文章h2样式。 (In this case it h2 but it actually concerns a lot of tags and a lot of css). (在这种情况下,它是h2,但实际上涉及很多标签和很多CSS)。

Example

HTML: HTML:

<h2>This is a default h2</h2>
<div class="article">
  <h2>This should use article h2 styling</h2>
  <p>Paragraph 1</p>
  <div class="gallery">
    <h2>This should use default styling</h2>
    <p>Paragraph 2</p>
  </div>
  <p>Paragraph 3</p>
</div>

CSS: CSS:

h2 {
  font-size: 30px;
  color: green;
}
.article h2 {
  font-size: 20px;
  color: blue;
}
.gallery {
  border: 1px solid #000;
  padding: 10px;
}

Working example: https://jsfiddle.net/sorenhusted/b774p8be/3/ 工作示例: https : //jsfiddle.net/sorenhusted/b774p8be/3/

You need the direct child selector > . 您需要直接子选择器>

Per MDN 每个MDN

The > combinator separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first. >组合器分隔两个选择器,并仅匹配第二个选择器匹配的元素,这些元素是第一个选择器匹配的元素的直接子元素。 By contrast, when two selectors are combined with the descendant selector, the combined selector expression matches those elements matched by the second selector for which there exists an ancestor element matched by the first selector, regardless of the number of "hops" up the DOM. 相比之下,当两个选择器与后代选择器组合在一起时,组合的选择器表达式将与第二个选择器匹配的元素匹配,对于这些元素,存在一个由第一个选择器匹配的祖先元素,而与DOM上“跳跃”的次数无关。

.article > h2 {
  font-size: 20px;
  color: blue;
}

JSFiddle Demo JSFiddle演示

Try: 尝试:

.article>h2 {
  font-size: 20px;
  color: blue;
}

Example: https://jsfiddle.net/b774p8be/4/ 示例: https//jsfiddle.net/b774p8be/4/

Direct child accessor ( > ) is your friend! 直接儿童访问者( > )是您的朋友!

In your CSS, just replace .article h2 with .article > h2 , and there you go :-) 在您的CSS中,只需将.article h2替换为.article > h2 ,然后就可以了:-)

Basically, it says that "only an h2 element which is a direct child of a .article element will be affected. 基本上,它说:“只有作为.article元素的直接子元素的h2元素会受到影响。

https://jsfiddle.net/b774p8be/6/ https://jsfiddle.net/b774p8be/6/

You can assign .article .gallery h2 to the same style used for default h2 likeso: 您可以将.article .gallery h2分配给用于默认h2样式,如下所示:

h2, .article .gallery h2 {
 font-size: 30px;
 color: green;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM