skip to Main Content

I have dozens of blog posts imported from a WordPress site, where they have used single bold lines as headings (without tagging them as such). This is my content example:

<p><strong>This is a heading. I want to apply some CSS to this line of text</strong></p>
<p>But I don't want it applied here<strong>or here</strong> because this a paragraph.</p>

All I want is to apply a margin-top to those bold sentences to clarify that they are headings of a section.

I cannot modify the HTML (ie change them for H3) as it would mean going over all posts manually. I need to stick to CSS to make the change.

I have tried this and it was a pretty good solution. But it wasn’t because the small paragraph in the example was being selected as well, as it only had one <strong> in it.

p:has(strong:only-child) {
    margin-top: 20px;
}

My thought was to find a way to EXCLUDE any <p> that had any "loose text" in it, apart of the single <strong> tag. But I don’t know how to say "loose text" to use it in a :not() pseudo selector.

I want this rule to affect only this margin: Image

I hope it makes sense.

2

Answers


  1. try this.

    .container>strong:first-child {
     color: red;
     margin-top: 10px;
    }
    <div class="container">
        <strong>This is a heading you want styles applied to</strong><p>but not here<strong> or here in this bold tag</strong></p>
    </div>
    Login or Signup to reply.
  2. A better solution to your problem would be to query the database with a <p><strong> change using a regular expression.

    If you still want to do it on the frontend, then you won’t be able to do this with css.
    I wrote one of the js solutions below. But I do not guarantee that it is perfect.

    document.querySelectorAll('p').forEach(p => {
      // exclude empty <p> or <p> is not has <strong>
      if (!p.hasChildNodes() || !p.querySelector('strong')) { 
        return;
      }
      const childNodes = p.childNodes;
      // check whitespace
      if (childNodes[0].nodeType === Node.TEXT_NODE || childNodes[childNodes.length - 1].nodeType === Node.TEXT_NODE) {
        p.innerHTML = p.innerHTML.trim();
      }
      if (childNodes.length === 1 && p.childNodes[0].nodeName === 'STRONG' && p.childNodes[0].textContent.trim()) {
        p.style.marginBlockStart = '20px';
      }
    })
    * {
      margin: 0;
    }
    <p> <strong>This is a heading with whitespace</strong></p>
    <p>But I don't want it applied here<strong>or here</strong> because this is a paragraph.</p>
    <p><strong>This is a heading</strong></p>
    <p>Lorem ipsum dolor sit amet.</p>
    <p><strong></strong></p>
    <p>Lorem ipsum dolor sit amet.</p>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search