Aligning Images In Markdown
- Published on
- -1 min read
Every post on this site is written in markdown since successfully moving over to GatsbyJS. Overall, the transition has been painless and found that writing blog posts using the markdown syntax is a lot more efficient than using a conventional WYSIWYG editor. I never noticed until making the move to markdown how fiddly those editors were as you sometimes needed to clean the generated markup at HTML level.
Of course, all the efficiency of markdown does come at a minor cost in terms of flexibility. Out of the minor limitations, there was one I couldn't let pass. I needed to find a way to position images left, right and centre as majority of my previous posts have been formatted in this way. When going through the conversion process from HTML to markdown, all my posts were somewhat messed up and images were rendered 100% width.
HTML can be mingled alongside the markdown syntax, so I do have an option to use the image tag and append styling. I wouldn't recommend this from a maintainability perspective. Markdown is platform-agnostic so your content is not tied to a specific platform. By adding HTML to markdown, you're instantly sacrificing the portability of your content.
I found a more suitable approach would be to handle the image positioning by appending a hashed value to the end of the image URL. For example, #left, #right, or #centre. We can at CSS level target the src
attribute of the image and position the image along with any additional styling based on the hashed value. Very neat!
img[src*='#left'] {
float: left;
margin: 10px 10px 10px 0;
}
img[src*='#center'] {
display: block;
margin: 0 auto;
}
img[src*='#right'] {
float: right;
margin: 10px 0 10px 10px;
}
Being someone who doesn’t delve into front-end coding techniques as much as I used to, I am amazed at the type of things you can do within CSS. I’ve obviously come late to the more advanced CSS selectors party.
Before you go...
If you've found this post helpful, you can buy me a coffee. It's certainly not necessary but much appreciated!
Leave A Comment
If you have any questions or suggestions, feel free to leave a comment. Your comment will not only help others, but also myself.