Naked Note Div.

Paragraph in Note DIV.

Second Paragraph in No" /> Naked Note Div.

Paragraph in Note DIV.

Second Paragraph in No" /> Naked Note Div.

Paragraph in Note DIV.

Second Paragraph in No"/>

Trouble with ::before,how to apply differently depending on contents of <div>?

39 Views Asked by At

Let's say I have:

<p>Paragraph.</p>
<div class="note">Naked Note Div.</div>
<div class="note">
  <p>Paragraph in Note DIV.</p>
  <p>Second Paragraph in Note DIV.</p>
</div>
<div>NON Note Naked Div.</div>
<div>
  <p>Paragraph in NON None DIV.</p>
</div>

I would then like to get the output:

 Paragraph.
 NOTE: Naked Note Div.
 NOTE: Paragraph in Note DIV.
 Second Paragraph in Note DIV.
 NON Note Naked Div.
 Paragraph in NON None DIV.

I have tried to use pseudo class ::before to achieve this but the fact that some divs have paragraphs inside and some don't makes it surprisingly difficult, at least for newbie me.

With: CSS .note::before {content: "NOTE: ";} I get:

 Paragraph.
 NOTE: Naked Note Div.
 NOTE:
 Paragraph in Note DIV.
 Second Paragraph in Note DIV.

With CSS .note :first-child::before {content: "NOTE: ";} I get:

 Paragraph.
 Naked Note Div.
 NOTE: Paragraph in Note DIV.
 Second Paragraph in Note DIV.

Is there any way to fix this with just CSS? That is not using a preprocessor or jquery or such.

1

There are 1 best solutions below

2
Temani Afif On

You can try with the :has() selector

.note:not(:has(*)):before, /* when it has nothing select the note element*/
.note:has(*) :first-child:before { /* when it has something select the first child*/
  content:"Note: ";
  color: red;
}
<p>Paragraph.</p>
<div class="note">Naked Note Div.</div>
<div class="note">
  <p>Paragraph in Note DIV.</p>
  <p>Second Paragraph in Note DIV.</p>
</div>
<div>NON Note Naked Div.</div>
<div>
  <p>Paragraph in NON None DIV.</p>
</div>

Until better support for :has() you can use float:

.note::before { 
  content:"Note:";
  color: red;
  float: left;
  margin-right: 10px;
}
<p>Paragraph.</p>
<div class="note">Naked Note Div.</div>
<div class="note">
  <p>Paragraph in Note DIV.</p>
  <p>Second Paragraph in Note DIV.</p>
</div>
<div>NON Note Naked Div.</div>
<div>
  <p>Paragraph in NON None DIV.</p>
</div>