Using CSS selectors is a clean way to implement this. I actually did it by modifying the HTML and adding CSS classes after the Markdown is converted to HTML. Here is some Ruby code which does this, using the Nokogiri gem. It handles inline images as well, just two next to each other side by side. The code assumes all the images are same width however, so it’s not going to fit every solution. And maybe cleaner solutions exist using just CSS.
require 'nokogiri'
html = Nokogiri::HTML.parse(html)
# Replace paragraphs wrapping the images with divs.
html.css('img').each do |img|
img.parent.name = 'div'
end
# Alternate between aligning the divs left, right, or in a side by side container.
div_class = 'left'
html.css('div').each do |div|
unless div.get_attribute('class') == 'footnotes'
image_count = 0
div.css('img').each do |img|
image_count = image_count + 1
end
if image_count == 2
div.set_attribute('class', 'sidebyside')
else
if div_class == 'left'
div.set_attribute('class', div_class)
div_class = 'right'
else
div.set_attribute('class', div_class)
div_class = 'left'
end
end
end
end
# Converts nokogiri variable to html.
html = html.to_html
And then use the following CSS to handle the floating of the image containers and their sizes.
div.left {
width: 298px;
float: left;
}
div.right {
width: 298px;
float: right;
}
div.sidebyside {
width: 621px;
}