Automatic Image Padding in Joomla!

The wysiwyg editors in Joomla! offer the option to align an image left or right in your article. However, by default these images will not have padding around them, and the may look squished against the text. Here's a solution I use the help deal with this issue...

Instead of adding any complex html and css into the article itself, this technique uses a few lines of css and some javascript to apply the correct padding to all images.

Update: Buddy Q has raised a good point, that you can just use img[align=left]{ /* styles */ } for browsers that support this. This is basically all browsers, except ie6.  If you still want a solution for ie6, the rest of this post may be useful...

Note: For optimal performance, you would want to avoid using the javascript at all, but it is a quick way to add the class to all existing images that have an align attribute. The best solution may be to set up the editor, or 'Add Image' button so that it will always add this class for you. Ideally, it should be as simple as selecting the alignment, and it takes care of the rest for you, with no need for additional javascript. But for what it's worth, this is a technique you may want to consider.

First, align the images in the normal way with the editor align option. Next, add this code to your template...

Mootools version

window.addEvent('domready', function() {
$(document.body).getElements('img[align]').each(function(i){
i.addClass( i.getAttribute('align') );
});
});

or jQuery version

jQuery(function($){
$('img[align]').each(function(){
$(this).addClass($(this).attr('align'));
});
});

What this does is find any image with an align attribute set, and add a class name based on the align value. So an image with align left, now also belongs to the class "left". I do this to keep it simple for the editors, so that they dont have to worry about adding a class in the article. But if you wanted to skip this step, and feel comfortable with adding a class to the image, that works just fine also.

Now that you have classes applied to these images, you can add the following css to your template...

img.left {
float:left;
margin-right:15px;
margin-bottom:10px;
}

img.right {
float:right;
margin-left:15px;
margin-bottom:10px;
}

2 Comments

Feed
  1. You could bypass the javascript and just use css since there is an attribute on the image itself...

    img[align=left]{ /* styles */ }
  2. Excellent! ..just what I was looking for, works perfectly, thanks!

Add Comment


  • >:o
  • :-[
  • :'(
  • :-(
  • :-D
  • :-*
  • :-)
  • :P
  • :\
  • 8-)
  • ;-)