0

I'm working on a theme for a travel blog and the author likes to insert small images in the text of their posts (an example is here).

I want the images to alternatingly float left or right (so the first image floats left then the next floats right, etc). I know with CSS you can use pseudo-classes like nth-of-type to apply styles to every other item but it doesn't seem to be working in this case because they aren't a bunch of sibling img items all next to each other, they're img items buried within paragraphs of the post.

How can I go about applying alternating styling to the images in the posts in this scenario?

closed as off-topic by TheDeadMedic, Howdy_McGee, Mayeenul Islam, bueltge, Pat J May 13 '16 at 17:53

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

0

Florian's answer is probably your best bet because it gives the author the most control as to how the images are aligned so that would be my first answer.

However, if you don't trust your authors to align the images themselves then we'll have to go another route. Unfortunately for the reasons you stated above, it doesn't look like we can use the :nth-child CSS since they are all nested within <p> tags.

So, we'll have to use a little bit of jQuery to make this possible:

$( document ).ready(function() {
    var imgCount = 0;
    $('.post-text img').each(function(){
        // remove our alignnone class for good measure
        $(this).removeClass('alignnone');
        // If the count is even, alignright, else align left
        if(imgCount%2 == 0){
            $(this).addClass('alignright');
        } else {
            $(this).addClass('alignleft');
        }
        imgCount++;
  });
});

This assumes that you are using jQuery and that you have the alignright and alignleft classes set in your CSS. I have a working version on jsfiddle.

**DO NOTE: this will grab every image inside of your post-text class, so if you use post-text anywhere else on your site and you load this JS, it will affect the rest of your site. I would recommend either adding a new class to your blog posts loop, or only loading this JS on the single-posts.php page so that this only affects your blog posts pages and nothing else on your site.

0

Have the writer use the left/right align functionality built into the WordPress text editor. The editor adds alignleft or alignright classes to the aligned images. Way more info can be found in the WordPress codex.

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