Working on some CSS for a WordPress site, I came across this:

img[class*="align"],
img[class*="wp-image-"],
img[class*="attachment-"] {
    height: auto; /* Make sure images with WordPress-added height and width attributes are scaled correctly */
}

Are thes wild cards that will work for any instance of, for instance, class="wp-image-a", class="wp-image-b", class="attachment-vacation"?

Dani AI

Generated

Good follow-up to ’s confirmation is a helpful start. A few practical tips and alternatives make this more robust and maintainable when WordPress is emitting variable class names.

You can narrow matches with other attribute operators when you need precision (examples below use different operators than the one in your snippet):

/* class starts with a prefix */
img[class^="wp-image-"] { max-width:100%; height:auto; }

/* class ends with a suffix */
img[class$="-left"] { float:left; }

/* match a whole space-separated token */
img[class~="align"] { display:block; }

/* match value or value-... (hyphen-aware) */
img[class|="attachment"] { border:0; }

Notes and pitfalls:

  • WordPress often concatenates modifiers (e.g., alignleft), so a whole-word token match (~=) won’t catch those — choose the operator that matches the real pattern.
  • Attribute-based selectors can be less explicit than a plain class selector and may produce false positives if other classes contain the same text. If you control the markup, prefer a predictable class name instead of relying on pattern-matching.
  • For maintainability, add a stable class at insertion time via a filter. Example for images generated by WP:
add_filter( 'wp_get_attachment_image_attributes', 'prefix_add_custom_class', 10, 3 );
function prefix_add_custom_class( $attr, $attachment, $size ) {
    $attr['class'] = ( isset( $attr['class'] ) ? $attr['class'] . ' ' : '' ) . 'site-image';
    return $attr;
}

Further reading on the selector syntax and edge cases is available from the MDN attribute selectors guide and the WordPress docs for the wp_get_attachment_image_attributes filter.

Yes correct. The *= will select those elements that contain that substring.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.