0

I can't really remember why this structure within CSS is used?:

h2.class-name

Seems that you could just write out .class-name and just give that the class for the h2:

<h2 class="class-name">Title thing</h2>

Unless the reason for it is if you cannot edit the HTML. So this would be it, right?:

<div class="class-name">
  <h2>Title thing</h2>
</div>

I guess I'm just "fuzzy" on what the reasoning would be for that particualr CSS structure.

1
  • 1
    There are plenty of uses so this question may be a bit broad by nature. In any event, here's an example... I have a page with active and inactive elements. I determine which elements are active by applying the class active in javascript, but I want active divs to look different than active h2s. I'd use h2.active and div.active to achieve element-specific styling, without requiring me to put a specific class on every element. Commented May 29, 2018 at 19:18

2 Answers 2

2

h2.class-name means, select all the <h2> elements that have the class 'class-name', consider the following:

p.red {
  background-color: red;
  color: white;
}

h2.red {
  color: red;
  text-decoration: underline;
}
<p class="red">
  RED PARAGRAPH
</p>

<h2 class="red">RED HEADING 2</h2>

Notice that both the <p> and the <h2> have the class 'red', but its implementation is different for each element, so if a <p> has the class 'red', style it this way, and if an <h2> has the class 'red' style it that way.

Sign up to request clarification or add additional context in comments.

Comments

2

There are lots of reasons someone might use that construct. The ones that spring to mind are:

  • To distinguish between members of the class-name class that are h2 elements and members of it which are some other kind of element.
  • To control specificity as h2.class-name is more specific than .class-name.
  • To make it clear to people reading the CSS what elements that class is supposed to be applied to

Unless the reason for it is if you cannot edit the HTML. So this would be it, right?:

No. That would require the use of the child or descendant combinators.

.class-name h2 {}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.