Tutorials

Floating images with proper margins

Floating (or aligning) images among text is a pretty common thing in content management. It’s pretty easy to do in Surreal:

  • Select an image
  • Select the align left/right button in the toolbar

Unfortunately, you normally end up with text cramping your image, which is very undesirable:

Floated image with no margin
Floated image with no margin

You could try to solve the problem by setting a margin with CSS, but not knowing if the image is floated left or right will leave you with a margin on both sides of the image. This really isn’t much better (margin highlighted in yellow):

Floated image with full margin
Floated image with full margin

Ideally, you only want the image to have a left margin when floated right, and a right margin while floated left:

Floated image with left margin
Floated image with left margin

But how do you do that with when the editor generates markup like this?

<img src="image.jpg" style="float: right;">

You could try styling it with a CSS attribute selector, but it wouldn’t be reliable if there were other inline styles applied to the image. You could tell your clients to only align images on the right, but that’s really not a great solution either.

Wouldn’t it be better if we just added a special class you can use to style images when they get floated left or right?

Float classes for images

Until now, we really didn’t have a good answer for how to tackle this problem. With the introduction of V5, your images will now receive a special class when they get aligned left or right:

<img src="image.jpg" class="cms-float-left">
<img src="image.jpg" class="cms-float-right">

Now you can solve this age-old problem with two simple CSS selectors:

.cms-float-left {
    margin-right: 20px;
}
.cms-float-right {
    margin-left: 20px;
}

Of course, you can apply whatever styles you like to these classes. It’s such a simple solution for a simple problem, it left us wondering why we didn’t come up with it sooner.