Centering Images with Jekyll and Markdown

Sunday, November 30, 2014

There are a handful of ways to center an image on a web page. The simplest method is to create a CSS class with the margin and display properties and apply that class to the image link.

However, when I write a post I’m writing it in Markdown and I don’t want to embed any sort of HTML or CSS in it. I want to keep the post free of markup and formatting instructions. But this is one of those situations where I need some sort of mechanism to simply apply a CSS class to an image. There had to be a simple way to do this without marking up the post with too many tags.

After Googling around for a bit, I found gerwitz’s comment in a Markdown and image alignment thread on Stackoverflow. Of all the other possible solutions I found, this one was the cleanest and least obtrusive.

This particular feature, called Attribute List Definitions, is an extension of standard Markdown and has been implemented in kramdown (it was first implemented in Maruku). Wherever you have your images linked to in the Markdown file, simply append the following syntax containing the CSS class you want to apply to the image link (in this example the CSS class is .center-image):

{: .center-image }

So, the entire image link would look like the following in your Markdown file:

![Picture description](/link/to/picture.jpg){: .center-image }

If you need to apply multiple CSS classes, simply add more delimited by a space:

![Picture text](/link/to/picture.jpg){: .center-image .example-class1 .example-class2 }

Then, somewhere in your style sheets you will need the following CSS class to actually center the image:

.center-image
{
    margin: 0 auto;
    display: block;
}

After you run jekyll build and view the generated website, images should have CSS class center-image and be centered on the web page.



comments powered by Disqus