sorenhusted
sorenhusted

Reputation: 15

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. I have tried using the :not() pseudo class, but it seems I can't use this for this problem.

I want to know if it's possible without overriding the article h2 styling. (In this case it h2 but it actually concerns a lot of tags and a lot of css).

Example

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:

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/

Upvotes: 1

Views: 1678

Answers (4)

Ronen Cypis
Ronen Cypis

Reputation: 21470

Direct child accessor (>) is your friend!

In your CSS, just replace .article h2 with .article > h2, and there you go :-)

Basically, it says that "only an h2 element which is a direct child of a .article element will be affected.

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

Upvotes: 1

Jack Nolddor
Jack Nolddor

Reputation: 43

Try:

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

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

Upvotes: 1

Paulie_D
Paulie_D

Reputation: 115288

You need the direct child selector >.

Per 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.

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

JSFiddle Demo

Upvotes: 2

onotype
onotype

Reputation: 61

You can assign .article .gallery h2 to the same style used for default h2 likeso:

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

Upvotes: 0

Related Questions