Custom CSS class for RichTextField images.

580 views
Skip to first unread message

Isaac Jordan

unread,
Feb 8, 2016, 4:59:25 PM2/8/16
to Wagtail support
I'm using RichTextFields inside of a StreamField on my blog. I'd like any images in the RichTextFields to be scaled using a Bootstrap CSS class ('img-responsive'), but I cant really find any documentation on how to add HTML classes to images.

Anyone got any pointers?

Thanks!

Matthew Westcott

unread,
Feb 9, 2016, 5:26:40 AM2/9/16
to wag...@googlegroups.com
Hi Isaac,
This can be done through 'image formats'. As standard there are three image formats available - the 'Full width', 'Left-aligned' and 'Right-aligned' options you see after selecting an image - and these are rules for determining how the chosen image gets resized and translated into the final <img> tag:
http://docs.wagtail.io/en/v1.3.1/topics/images/using_in_templates.html#images-embedded-in-rich-text

You can define your own formats, or replace the existing ones, as described here:
http://docs.wagtail.io/en/v1.3.1/advanced_topics/customisation/page_editing_interface.html#rich-text-image-formats
In particular, you can update the default formats to include an 'img-responsive' class by creating an 'image_formats.py' file inside one of your project's apps, containing the following:


from wagtail.wagtailimages.formats import Format, register_image_format, unregister_image_format

unregister_image_format('fullwidth')
unregister_image_format('left')
unregister_image_format('right')
register_image_format(Format('fullwidth', 'Full width', 'richtext-image img-responsive full-width', 'width-800'))
register_image_format(Format('left', 'Left-aligned', 'richtext-image img-responsive left', 'width-500'))
register_image_format(Format('right', 'Right-aligned', 'richtext-image img-responsive right', 'width-500'))


Cheers,
- Matt

Isaac Jordan

unread,
Feb 9, 2016, 2:17:00 PM2/9/16
to Wagtail support
Thanks again Matt. That solution works.

The only issue is that the img-responsive class breaks the left and right alignment of the images. Text just appears below the image. 
So I've only added the class I want into the Full-Width format (not a problem as I'll likely only use that format anyway).
Reply all
Reply to author
Forward
0 new messages