CSS Wildcards for More Tamper-Proof Post Content Styling

I’m building a client site, and I wanted to write a couple of CSS rules:

  1. “Anytime a paragraph is directly after an <h2> element, I want it to have special styling.”
  2. “I want any <h2> with an ID—whatever it is—to have special styling.”

Handling this with classes felt scary, because the client could remove those classes somehow. Here are the rules I wrote:

/* Style any h2 with an ID */
h2[id] {
    /* Styling */

/* Style any p after an h2 */
h2 + p {
    /* Styling */

So I’m linking to a very good Stack Overflow post on wildcard characters in CSS (which I used as the basis for my ID styling), but I highly recommend that you read into CSS pseudoselectors more broadly. The end result, more often, is a site that just works without having to worry about the client breaking post contents, and that’s a happy story.

Add a Comment

Your email address will not be published.