Jonathan Russell
Jonathan Russell

Reputation: 37

Using CSS to change a class background but only if it is not after a h4

I am trying to change the background colour of PARAGRAPH 4 only. I want to leave Paragraph 2 alone (because it is after a H4). I have tried the not selector but can't seem to get the logic working right. Not wanting to use JavaScript, PHP or jQuery. Only pure CSS please.

.widget-wrap > .widget-title {
  background-color: yellow;
}
.widget-title + .textwidget {
  background-color: red;
}
<div class="widget-wrap">
  <h4 class="widget-title">Paragraph 1 in the div.</h4>
  <p class="textwidget">Paragraph 2 in the div.</p>
  <p>Paragraph 3 in the div.</p>
</div>

<div class="widget-wrap">
  <p class="textwidget">PARAGRAPH 4 INSIDE 2ND DIV.</p>
  <p>PARAGRAPH 5 INSIDE 2ND DIV.</p>
</div>

Upvotes: 2

Views: 168

Answers (3)

user2906608
user2906608

Reputation: 123


Why you being not using different class name or id for the paragraph 4. that will be more simple and crystal clear. I would rather suggest you to use. In current code as class names are same for parent div and P hence the color is changing for all not only for h4. sl please kindly use these. Html

<div class="widget-wrap">
<p class="textwidget redcolor">PARAGRAPH 4 INSIDE 2ND DIV.
</p>
<p>
PARAGRAPH 5 INSIDE 2ND DIV.
</p>
</div>

CSS:

 .widget-wrap .redcolor {
 background-color: Red !important; /*use important if not works*/
 }

so now all elements having class redcolor inside class widget wrap will be having background color red. you can use id or any other class name. that will be more easier and best approach for than using the any other javascript etc.

It will add more css lines but that will not cause any harm to it.

Upvotes: 0

Jayesh
Jayesh

Reputation: 569

check this out

.widget-wrap:nth-child(2) .textwidget {
  background-color: green;
  color: white;
}

Upvotes: 0

BoltClock
BoltClock

Reputation: 724102

If the first child of .widget-wrap will only either be an h4.widget-title, or a p.textwidget (i.e. when the h4 is not present), simply use :first-child:

.widget-wrap > .widget-title {
  background-color: yellow;
}
.widget-wrap > .textwidget:first-child {
  background-color: red;
}
<div class="widget-wrap">
  <h4 class="widget-title">Paragraph 1 in the div.</h4>
  <p class="textwidget">Paragraph 2 in the div.</p>
  <p>Paragraph 3 in the div.</p>
</div>

<div class="widget-wrap">
  <p class="textwidget">PARAGRAPH 4 INSIDE 2ND DIV.</p>
  <p>PARAGRAPH 5 INSIDE 2ND DIV.</p>
</div>

If there any other elements may appear before the first p.textwidget absent an h4.widget-title, that will complicate things slightly. You would use :not() with a sibling selector in that case, but if there can be a variable number of elements, you won't be able to do this reliably.

Upvotes: 4

Related Questions