Search code examples
htmlcsstags

Can I wrap tags around an element in CSS?


For example, could I wrap all <p> elements in <b> tags so <p>Hello</p> would be rendered as if it were <b><p>Hello</p></b>?

I tried using ::before and ::after like this:

p::before {
    content: "<b>";
}
p::after {
    content: "</b>";
}

but the tags were escaped. Is there some way to do this?


Solution

  • No. This would be a misuse of CSS. CSS is not designed to alter markup, but to augment it with styling. If you could do what you are suggesting, we developers would all be in a living hell. You have some options:

    Option 1

    • Wrap the content you want to make bold in a container
    • Give that container a class
    • Write a CSS class to make that container's content bold

    e.g. Original HTML

    <html>
      <h1>My content<h1>
    </html>
    

    New HTML

    <html>
       <section class="bold">
          <h1>My content<h1>
       </section>
    </html>
    <style>
    .bold {
      font-weight: bold
    }
    </style>
    

    Option 2

    • If you can't alter the markup
    • Find a selector that will select the content you want
    • Write a CSS class to make that container's content bold
    <html>
      <h1>My content<h1>
    </html>
    <style>
    h1:first-of-type { 
      font-weight: bold
    }
    </style>
    

    Note the :first-of-type for an example of specificity selector.