Search code examples
htmlcsscss-selectorspseudo-elementpseudo-class

Only-child pseudo-class for first-line pseudo-element


Is there a way to avoid the "red highlight" in the last example?

Live Demo

<h3>should be:</h3>

    <div class="demo">
    <p>foo foo</p>
    <p>bar bar</p>
    </div>

<hr>

    <div class="demo">
    <p>foo foo<br>foo foo</p>
    <p>bar bar</p>
    </div>

<hr>

    <div class="demo">
    <p>foo foo<br>foo foo</p>
    </div>

<h3>should not be:</h3>

    <div class="demo">
    <p>foo foo</p>
    </div>

This is what I currently use:

.demo p:first-child::first-line {
    color: red;
}

But, it highlights all examples, including the last one. I also tried these two:

.demo p:first-child::first-line:not(:only-child) {
    color: red;
}

/* and... */

.demo p:first-child::first-line:not(:only-of-type) {
    color: red;
}

But it seems it just brokes all the highlight in all demos.

Is there way to achieve the desired result? (Remove "red highlight" from the last example).

(JS/jQuery solution is also ok, but, if it could be solved with CSS, it would be much better).

Screenshot with desired result:

enter image description here


Solution

  • I have a solution in jQuery.

    CSS:

    .demo p:first-child:first-line {
      color: red;
    }
    .demo .not-red:first-line {
     color: green !important;
    }
    

    JS:

    $('.demo p:only-child:not(:has(br))').each(function() {
      $(this).addClass('not-red');
    });
    

    JS will add not-red class only to paragraphs that doesn't contain br tags and paragraphs that are only child.

    CODEPEN