4

I need to select <b> tags but only if that is the only content inside of a <p>. So for example, select the b in <p><b>hello</b></p> but not in <p><b>hello</b> world</p>. Is this possible? :only-child doesn't do it.

2 Answers2

0

CSS selectors are clueless about text nodes.so, use span element for content like this:

<p>
  <b>hello</b><span>world</span>
</p>
<p>
  <span>world</span><b>hello</b>
</p>
<p>
  <b>hello</b>
</p>


p b:only-child{
  color:red;
}

The "only-child" selector selects an element if it is the only child of its parent. The term "child" refers to elements that are not simply text.

For first "p" children are "b" and "span".

For second "p" children are "b" and "span".

For third "p" children is only "b"

only "b" of last "p" will be selected

<p>
  <b>hello</b>world ===> children is only b;
</p>
<p>
  world<b>hello</b> ===> children is only b;
</p>
<p>
  <b>hello</b> ===> children is only b;
</p>

all "b" elements will be selected

-1

You can simply find a common class for all tags you want to change and insert it inside the element (< b class="">). In the CSS you can then edit the class according to your wishes.

Eduard
  • 141
  • 7