Styling paragraphs in nested divs

I have something like this

<div class="main">
   <p>text text</p>
   <div class="content">
      <p>text text text</p>

How can I style the two paragraps differently. What I’ve got now just makes the first paragrap style .main p overide the .content p


That should not be the case.

.main p {
  color: red;
.content P {
  color: blue;

What css do you have?

Since they have equal specificity, order could affect it, .content p should be last.

1 Like

maybe I need to clean up my css sheet, but it does overide. I just changed to

div.content p

and now it seems to work.

That’s because you increased the specificity.
I’m guessing it was the order at fault.

1 Like

Agreed. I’m betting you had something like this with content coming first in the css…

.content p { color: red;}
.main p { color: blue; }

Remember that they are called cascading style sheets for a reason. All things being equal, the last item that matches will be used.


Thats right :smiley: Thanks guys

This is perfect opportunity to learn the basics of CSS specificity .

In short, the key thing is that it is the complexity of the selector and the order in the stylesheet which effectively determine what element is targeted.

I would bet , in your original Q, that .main p is after .content p in your stylesheet. Since both rules have the same specificity the second merely overrides the first.

This may not apply to your current case, BUT…
If you are able to alter (simply your source code) you could do:

<div class="main">
   <p>text text</p>
    <p>text text text</p>

 .main p /* .main p rules*/
 .main p + p /* .content p rules; you could also do .main p ~ p */

You save an extra div tag, and class name. do note, as long as we are on the subject of specificity that .main p + p > .main p . :slight_smile:

hope that helps


I’m a visual person, so I’ve always preferred this infographic I found a couple years ago (the fact that it’s using star wars never hurts imho :smiley: )


Thanks, this is very interesting. I will definitely check it out!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.