How to apply CSS style if the p element does not have a ul

535 views Asked by At

I want to apply the page-break-inside:avoid property to all p elements that do not have a ul element.

p {
    margin-top: 4pt !important;
    margin-bottom:6pt !important;
    page-break-inside:avoid;
    orphans: 4;
    widows: 2;
}
<p>Hello text </p>
   <p>hello <ul>
    <li>list </li>
   </ul>

I want to exclude the second paragraph. Is it possible through CSS? I am looking for a CSS solution.

2

There are 2 answers

0
Mihail Minkov On

You can't use the ul inside a p element. As for the identifier topic, the only option for this would be to use the :has pseudo class, but it's still not compatible.

You can check its documentation here.

Revise your code to improve the structure.

What you could do is something like this:

<p>First paragraph</p>
<p>Second paragraph</p>
<ul>
   <li>Element 1</li>
   <li>Element 2</li>
</ul>
<p>Third paragraph</p>
<p>Fourth paragraph</p>

This way if you want to affect a ul that's right after a p you could use this selector:

p ~ ul {
   color: red;
}
//Selects every <ul> element that are preceded by a <p> element
0
magicDev On

Your code is not valid. p elements can only contain phrasing content https://html.spec.whatwg.org/multipage/grouping-content.html#the-p-element