Jekyll Blog Post: Centering Images

Say you have a blog site with Jekyll and the blog posts are centered on the page. I want content (i.e. paragraphs, words, code, etc.) to be aligned to the left, but images to be centered.

I have the text, etc. left-aligned, but now I'm struggling to get the image (who has a CSS style of max-height: 80%) to be centered as well.

It appears that Jekyll's blog generator (from Markdown) wraps images in <p></p> tags so margin: 0 auto doesn't center the image. I've attached code snippets below:

<li>
    <h2 class="post-title">Hello World</h2>
    <div class="post-date"><span>May 21, 2014</span></div>
    <div class="post-content">
        <p><img src="/images/photos/blog/hello-world.jpg" alt="blog-image"></p>
    </div>
</li>

ul#posts {
  list-style-type: none;
  margin: 0 auto;
  width: 60%;
}

ul#posts > li {
  margin-bottom: 35px;
  text-align: center;
}

ul#posts > li div.post-content {
  text-align: left;
}

ul#posts > li > div.post-date {
  color: #A0A0A0;
  font-style: italic;
  margin-bottom: 15px;
}

ul#posts > li > div.post-content > p > img {
  margin: 0 auto;
  max-height: 80%;
  max-width: 100%;
}

How can I center the image in the blog post?


Solution 1:

Here is a way to do it via kramdown:

{:refdef: style="text-align: center;"}
![My Image]({{ site.baseimg }}/images/example1.png)
{: refdef}

This will create another paragraph around the paragraph added by kramdown. Source

Solution 2:

I had to do the same in markdown on drupal and this solution worked for me though.

I aligned my images to the right by adding inline CSS like this:

<div style="text-align: right"><img src="/default/image/sms.png" width="100" /></div>

For aligning your image to the right or center, replace

<div style="text-align: right">

to

<div style="text-align: center">