Monday, 8 December 2014
Tips for Styling Code in your Posts
If you’ve ever included snippets of code on your blog, you know that presenting that text can be a unique challenge. HTML provides a tag for this purpose, the tag. Unfortunately, just chucking your code in those tags isn’t the end-all solution. For one thing, you typically need to turn off your Rich Text editor and hand-write them in if you want to get those tags at all. For another, if you are including actual HTML code in your sample, those tags will still render as HMTL, not text.
What does the code tag actually do?
Not a whole heck of a lot, actually. By default, it’s an inline element. Meaning you can use it just like tags or spans or whatnot. Also by default, it changes the font-family to a mono-spaced font like Courier or Monaco. For starters, you may want to consider changing it to a block-level element (display: block;) and adding some padding/margin/background/stroke to it’s CSS to emphasize the code to your readers. Sticking with the mono-spaced font is a good idea though. Something very “codeish” about that.
Like I mentioned, if you are including HTML code in your code blocks, you will need to replace your characters with >. This will stop your browser from seeing those as actual tags and it will render as regular text. If you have large amounts of code to do this to. You may want to consider a GREP solution (advanced Find/Replace).
Now you have your code all looking nice on the page, but one thing that can still remain a problem is the spacing. Good code is usually full of indents to visually break up sections. As you likely know, multiple concurrent spaces will not render in HTML. You can always force spaces with or other similar spacing codes, but there is a much simpler solution.
Using in conjunction with the pre tag
The tag (short for pre-formatted) is essentially for preserving spacing in text blocks. Wrap your code block in pre tags and apply spacing as normal to your code and it will display properly. Multiple spaces and tabs will be rendered as such.
Automating the process
Since we are dealing with blogs here, thankfully there are some plugins to make displaying code blocks in your post easier. Code Markupis a plugin for WordPress that allows your HTML markup within code tags to be displayed without having to replace all the ’s. It also has the nice feature of allowing some html tags to be rendered and some not to be, if you choose.
If anyone knows of other plugins that help with this, I’d love to hear about them.
TheoBloggingtips com
No comments: