How can I add a CSS class to all images inserted into a rich text field ?

ie. so an image inserted has style= "image fit" added to the img selector

3 Answers 3


I wrote a plugin called Retcon HTML which will solve this nicely using PHP's DOMDocument class.

You'll want to use the attr filter, which is documented here:

{{ entry.richTextField | retconAttr( 'img', { 'class' : 'image fit' }) }}
  • 1
    This is a really clean solution, thank you very much.
    – Masiorama
    Oct 19, 2015 at 9:11

I found this to work quite well for adding Bootstraps "img-fluid" class automatically:

{{ entry.yourTextField|replace('<img ', '<img class="img-fluid" ')|raw }}

There's a plugin that's supposed to do what you want: Redactor Add Attributes, but unfortunately it doesn't work with Craft newer that 2.0 (which includes the completely refactored Redactor 10).

  • Nope, sorry for that. If anyone has the time to make the necessary adjustments, I'd be more than happy to update the plugin.
    – Paul
    May 27, 2015 at 10:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.