Skip to content

Simple code highlighter using only CSS

Over the last 10 years, I have learnt that sharing code on websites can be tricky. Just yesterday I was working on a blog post and realized that anything between the <code></code> can look ugly if not styled properly.

For example, after writing some bash code within the post, it looked quite ugly:

Now, I just investigated how my CSS looked like. And the CSS to style it was barebones, like this

code,
kbd,
tt,
var {
font: 15px Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace;
}

Clearly, not acceptable and it looked plain and ugly. I didn’t want to use third party JS based highlighter and wanted to use clean CSS approach. I don’t need complex syntax highlighting and basically didn’t want to mess with simplicity and cleanliness of my site. In short, no time for bullshit. So here is what I did

code,
kbd,
tt,
var {
font: 15px Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace;
background: #eee;
color: black;
margin: 20px 0;
display: block;
padding: 20px;
}

Now, that’s more like it and it would simply add some nice greyish background, fix some margins and padding around the code and in a way, highlight it so it’s well separated from the general text. Problem solved! Nice and simple.

My cache wouldn’t clear automatically, so I simply cleaned the browser cache but had already tested with the incognito mode, the best way to test websites while you are developing them for a new customer base or just want to see quick results instead of cleaning the browser cache.  Here is the final result:

This works perfectly on the white background of my site. I am a happy man and all it took was 20 minutes to do that and also write this blog post about it. A quick lesson in usability and user experience 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *