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
As soon as I posted this question, I found the answer. CSS3 has an amazing
:only-child
selector.My solution:
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:
So if you want to have an own selector for three childs, you have to add one extra
nth-child
like this: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
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:
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:
And your formattingClass could be any CSS:
You can also do all of this with plain JS as well if you do not want to use jQuery.