Home > Net >  With CSS, style a div's text node (innerText), and exclude if it's a p element
With CSS, style a div's text node (innerText), and exclude if it's a p element

Time:01-13

Given the following HTML:

<div >
  should be bold (text node)
</div>

<div >
  <div>
    should be bold
  </div>
</div>

<div >
  <h3>
    should be bold
  </h3>
  <p>
    should not be bold
  </p>
</div>

<div >
  <p>
    should not be bold
  </p>
</div>

<div >
  <div>
    <p>
      should not be bold
    </p>
  </div>
</div>

The following styles the text node, but then also styles ALL descendants:

.container {
  font-weight: bold;
}

The following almost does the trick, except that 'A. should be bold' is not bold:

.container {
  &:first-child:not(p) {
    font-weight: bold;
  }
}

As soon as you use a selector, such as .container *, then the innerText will get excluded:

.container {
  * {
    font-weight: bold;
  }
}

I know this can easily be done with a class '.bold', but it needs to be dynamic. And ideally without overriding any styles because in the application the element get's some additional styling as well which I don't want to have to overwrite.

CodePudding user response:

Try this :

.container {
  font-weight: bold;
}
.container p{
  font-weight: normal;
}

Edit :

I will suggest this, but if you put just some text it will rendered like it has a <p>...

.container *:not(p) {
  font-weight: bold;
}
<div >
  A. should be bold
</div>

<div >
  <h3>B. should be bold</h3>
  <p>C. should not be bold</p>
</div>

<div >
  <p>D. should not be bold</p>
</div>

CodePudding user response:

Found a similar example: enter image description here

  •  Tags:  
  • css
  • Related