Centering Images with Jekyll and Markdown

• Updated March 8, 2018


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 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.

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).

In your 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 classes 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 be centered on the web page with CSS class center-image applied.

If you found this post useful and would like to help support this site - and get something for yourself - sign up for any of the services listed below through the provided links.

The following links are part of affiliate programs, and I will receive a referral payment from any of the services you sign-up for.

  • Get Faster Shipping: About to order some stuff on Amazon but want to get more value out of the money you would normally pay for shipping? Sign-up for a free, 30-day trial of Amazon Prime to get free two-day shipping, access to thousands of movies and TV shows, and more.
  • Start Investing Now: Looking to start investing some of your saved income? Get started by opening an account with Webull, where upon sign-up and opening a brokerage account with an initial deposit of $100 or more you will receive free stock(s). The promotions are always changing, so be sure to click the link to see the latest.

Thanks for reading and take care.