skip to Main Content

I’m working on a blog that will be image-heavy. I thought it would be nice to set up some CSS so that if two images are inserted in a post one after another, it will display them side-by-side. If only one is inserted, then it displays it full width.

I’m struggling with finding a way to apply the styling to both elements. Of course if there would always be two images, I could do the following:

span>img, span>img+img {width: 50%;}

But if there’s only one image then that span>img with make it half-width rather than full-width. I can’t change the code structure. It’s a Shopify blog and I want it to be as simple as possible for the client to use the built in editor.

Any help is appreciated.

3

Answers


  1. Chosen as BEST ANSWER

    As soon as I posted this question, I found the answer. CSS3 has an amazing :only-child selector.

    My solution:

    span>img:only-child {width: 100%;}
    span>img, span>img+img {width: 50%;}
    span>img {padding-right: 10px;}
    span>img+img {padding-left: 10px;}
    

  2. I hope this is what you need.

    You can choose the :nth-child() selector to use different styles for different child-count.
    Here’s how you do it:

    /* one item */
    li:nth-child(1):nth-last-child(1) {
        width: 100%;
    }
    
    /* two items */
    li:nth-child(1):nth-last-child(2),
    li:nth-child(2):nth-last-child(1) {
        width: 50%;
        float: left;
    }
    

    So if you want to have an own selector for three childs, you have to add one extra nth-child like this:

    /* three items */
    li:nth-child(1):nth-last-child(3),
    li:nth-child(2):nth-last-child(2),
    li:nth-child(3):nth-last-child(1) {
        width: 33.3333%;
        float: left;
    }
    

    And you can keep increasing the child-count.
    You can read more on it here: Styling elements based on sibling count

    And here’s a working fiddle with some fancy pictures: JSFiddle

    Login or Signup to reply.
  3. Best way would be to use a CSS framework that has a grid system designed to handle this sort of scenario such as Bootstrap or Foundation. But if thats not what you want…

    Easiest way in my opinion would be to use JQuery:

    var numOfImages = $(".some_class > img").length
    

    Would get you the number of images nested inside “some_class.”

    Then you can check the number of images and apply a CSS class that does exactly what you want:

    if(numOfImages > 1) {
         $(".some_class > img").css('formattingClass');
    }
    

    And your formattingClass could be any CSS:

    .formattingClass {
         width: 50%;
    }
    

    You can also do all of this with plain JS as well if you do not want to use jQuery.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search