0

I'm quite new to CSS and HTML and came across a situation where I have a class example and a class credits. I want some elements inside example to have a specific design, but credits is general and should apply to the whole document. So I wrote:

.example p {
    text-align: justify;
}
.credits {
    text-align: right;
}
<div class="example">
    <h1>Main Title</h1>
    <p class="credits">by Author</p>
  <p class="intro">some info...</p>
  <h2>Title</h2>
  <p>Lots of text...</p>
</div>

My problem is: .credits style is not applied to <p class="credits"> element inside the <div> and I don't understand why. Can someone explain me the reason?

sandmann
  • 188
  • 11
  • It happens because of you have already assigned ```text-align: justify;``` to the ```p``` element which will be taken with priority and hence the same ```p``` element class css selector ```text-align: right;``` is not assigned.. What does your exact requirement?? Do you want to move ```by Author``` to the right?? – Maniraj Murugan Mar 01 '20 at 14:51
  • @ManirajMurugan thanks for the feedback. I'm still getting used to how cascading works and didn't realize that `.example p` is more specific than `.credits`. I'd like to know how can I get `.credits` rules apply to "by Author" (in this case move "by Author" to the right). – sandmann Mar 01 '20 at 15:00
  • Have you looked at `!important` ? https://css-tricks.com/when-using-important-is-the-right-choice/ – JGFMK Mar 01 '20 at 15:01
  • @JGFMK not yet. Going to take a look at that right now. Thanks for the tip. – sandmann Mar 01 '20 at 15:04
  • I do want to call out that `!important` should be used very sparingly, as @JGFMK's article says, while it works, it often causes you far more issues down the line. – Nick Q. Mar 01 '20 at 15:10

1 Answers1

2

You're running into an issue with CSS selector specificity.

While CSS evaluates rules from top to bottom of the stylesheet, it also looks at selector specificity to determine which rule to apply first, second, third, and so forth.

The selector .example p has a higher specificity (two selectors) than the selector .credits therefor its being applied second and overriding the later selector.

If you update the second selector to have more specificity, (e.g. .example .credits) it will give you the output you're looking for.

.example p {
    text-align: justify;
}
.example .credits {
    text-align: right;
}
<div class="example">
    <h1>Main Title</h1>
    <p class="credits">by Author</p>
  <p class="intro">some info...</p>
  <h2>Title</h2>
  <p>Lots of text...</p>
</div>
Nick Q.
  • 3,734
  • 2
  • 21
  • 36
  • I'm still getting used to how cascading works and didn't realize that `.example p` is more specific than `.credits`. Thanks for the answer. – sandmann Mar 01 '20 at 15:08
  • It can definitely be tricky and selector specificity is one of those weird "gotchas" that end up tripping up a lot of folks. Glad it was helpful! – Nick Q. Mar 01 '20 at 15:09