Quick tip: use classes for image alignment in CKEditor

Posted on 04/07/2016

Easy image alignment is something that will annoy most content editors. If an image is aligned left, text wrapping on the right side will never be spaced properly.

The solution is of course to add appropriate margins, either by adding a custom CSS class or by adding inline styles - but content editors will always find this awkward.

Here's a small JS snippet that will work around this issue:

  1. // Add alignment classes for the images in content.
  2. $('#your-content-selector img').each(function() {
  3.   var $this = $(this);
  4.   if ($this.css('float') === 'left') {
  5.     $this.addClass('float-left');
  6.   }
  7.   else if ($this.css('float') === 'right') {
  8.     $this.addClass('float-right');
  9.   }
  10. });

Then in your CSS file you could have something like this:

  1. img.float-left {
  2.   float: left!important;
  3.   margin: 6px 12px 10px 0!important;
  4. }
  5. img.float-right {
  6.   float: right!important;
  7.   margin: 6px 0 12px 10px!important;
  8. }

The !important is necessary to override the floating styles added by CKEditor or whichever WYSIWYG you are using.

If you feel like improving, feel free to do so here. I might come back to it later, but it works just fine at the moment.