How to display code fragments in web pages
080219
Since in this blog I'll be writing about JavaScript, XHTML, CSS and other languages, I was wondering which would be the best way to display code fragments in a web page. Obviously each fragment will go inside a CODE element, but there's other things I'd like to implement:
- When the page is displayed without CSS, I'd like the code fragment to have a decent formatting.
- I'd like to add a sort of caption to each code block, to add things like "add this to your .css file" (see the code fragments below as an example).
And of course, I'd like to do it with the cleanest possible XHTML. Let's go!
Point 1 is easy to solve: all we need to do is wrap the CODE element inside a PRE element. An alternative would be to use BR elements inside CODE to format the code, but that looks ugly and inconvenient to me. Styling the CODE element to behave as a PRE element is not good, because it will ruin the code layout when viewed without CSS.
Just a note on PRE: in theory we shouldn't use PRE since it doesn't have semantic meaning, but I choose to use it anyway because it will force the browser to keep the code formatting even without CSS. To me this is an acceptable compromise, but I'd be interested to know other people's views on the matter.
Point 2 is debatable: should we use a P element inside PRE, just before CODE? Or outside PRE, adding a class to it? Then I had a curious idea: what about using the title
attribute in CODE, and use JavaScript to turn it into a visible caption? That sounds reasonable! The XHTML will stay nice and clean, and even without JavaScript the information will be there, as a tooltip. The result is a simple JS function that adds a DIV with class="JScodeCaption" just before the PRE element. Also, for easy styling, the class JS is added to the PRE element.
function addCaptionsToCode() {
var codes = document.getElementsByTagName("code");
var elTitle, elPre;
for (var i=0, l=codes.length ; i<l ; i++) {
title = codes[i].title;
if (title) {
// Remove title from CODE
codes[i].title = "";
// Prepare caption DIV
elTitle = document.createElement("div");
elTitle.innerHTML = title;
elTitle.className = "JScodeCaption";
// Add class to PRE
elPre = codes[i].parentNode;
elPre.className += " JS";
// Insert before the PRE
elPre.parentNode.insertBefore(elTitle, elPre);
}
}
}
Btw, if using innerHTML annoys you, feel free to use the appropriate DOM methods, I'm just too lazy... :)
<pre>
<code title="The caption for this block">
... some code here ...
</code>
</pre>
If you'd like to use it in your projects, simply run the addCaptionsToCode function with your method of choice (onload, DOMContentLoaded, at the end of the XHTML), and style the JScodeCaption class in your CSS file. Easy! I'll leave you with a sample CSS to style your code fragments (explaining it would be outside the scope of this post).
pre {
display: block;
margin: 2em 0;
white-space: pre;
overflow: auto;
width: 470px;
line-height: 1.4;
border: 1px solid #ccc;
background: #ece9d8;
padding: 8px;
}
/* JS: adding CODE captions */
pre.JS {
margin-top: 0;
}
.JScodeCaption {
margin-top: 2em;
color: #999;
font: .9em "Verdana", sans-serif;
padding-bottom: .2em;
}
Posted in: English, Web, JavaScript
Tags: programming
Hey I like your website and I look forward to reading about some CSS and btw can you write some tutorials using Frontpage 2001 (you can delete this silly comment if you like)
Hi South Coast CSS Wave Warrior (that would be SCCSSWW?)
Yes, I'm planning to start a FP dedicated blog, something like "Front Page is THE WAY". Will keep you updated.
I think I will delete these two comments, this is supposed to be a serious blog after all... but since yours is the only comment at the moment, it has to stay. Plus, you get a free dense13 T-shirt and some 'CSS Waves Wax' for your surfboard. ;)
B4 you delete these posts can I say This website ROCKS! I can wait to get my CSS wax to keep me standing strong in the slippery waves of cross web browser conditions. fROntpAGe or Die
(next time I will post something more sensible)
Am I sensing some sort of nepotism at work here? I want a t-shirt too :P
Am I to assume all the code that appears here uses that method? Just to be annoying, I thing code should go with some sort of colour code..
Frontpage? Seriously? I've never used anything more irritating...apart from Word I think, I am sure it is possible to make it "work for you" but didn't seem worh the trouble having something like Dreamweaver for example, that doesn't decide that your code is wrong and rewrites it without asking :-/
Hi Natalia,
South Coast CSS Wave Warrior is a friend down here in the South Coast, and he did not receive any shirts or wax, not until he abandons his addiction to Front Page... :) Actually, the whole Front Page thing is a joke. What would we do without M$? Who would we criticise?
Back to topic, yes, this blog uses this method for code fragments. And I agree with you about syntax coloring, that's in my TODO list for the blog. My CODE elements have a class indicating the language, so I can further on add the color coding with JavaScript.
Hei, I am not just slagging off my dear, I was actually "forced" to use Front Page for a project once, it is a nightmare I tell you!
Speaking of which I have to let you, if you have never used it, Eclipse is the best thing since sliced bread ;)
Wouldn't some sort of server side processing make more sense for the colour coding?
You might be right, doing the color coding on the server side, I’ll think about it.
Hey, syntax highlighting in code blocks ready! For now, I'm using a JavaScript library, for two reasons: first, it keeps my XHTML code clean, and also because it works on CODE elements, which is my preferred way to add code - which you already know, since you've read this article. ;)
Formatting code and keeping the page clean. Simple!!! Just fill the
page with lots of characters and use Courier font. Simple,
clean, impressive...just like me. (Cough) ;))
That last space should have shown "non-breaking-space characters".
Blimey.
Well, you joke about it, but I just got a CSS job that's all Courier. And basically on a plain white background. Someone's stealing your ideas...
What's the problem with the non-breaking-sapce characters? If you want email me with what you wanted to achieve, I'd like to improve the comments system in the blog to allow people to format text the way they like, so all feedback is appreciated.
Hmmm. Well I attempted to input the entity string for a
non-breaking-space but it disappeared in my submitted comment
above. I know nothing of the allowable characters in these blogs so
am a complete "newbie". Being a plain text email man, you would, I
should have thought, be opposed to allowing rampant formatting of
blog submissions. If you insist though Gonzalo, could you perhaps
allow me to add RED text in font point sizes up to 250 pt so I can
emphasize more in future comments?!! (Sorry, I am having a "silly"
day, unlike my usual steady and diligent self)...
Well, I definitely could do that if I was using my CMS (coming soon! Well, not so soon actually), but WordPress is very fussy about how to process input (and sometimes a bit annoying, I will add). But still, I'll probably have a look at the nbsp issue sometime.
For now you'll have to put up with just SHOUTING IN CAPITAL LETTERS if you need emphasis. :)
W H A S S A T ? ? ! !
[...] code posting method :) After searching around google for
a bit I found a guide which gave some great CSS for posting code in
a blog type environment. I have taken bits of pieces [...]
how do u make the comment part please help me thxs
How do you put this in for people to write in. E.g the comments
Hi yagami, I'm not sure what you mean, can you be more specific?
Is there any other way (except <code> and [code]) to display html
codes on the web page?
[...] and if you have any suggestions to help me improve my method,
please leave a comment! Resources: dense13.com Follow [...]
@Hawk: are you sure CDATA is the right option for the code tag? This is not actual code, but text representing code. I think the way to do it is by using entities for any non-valid characters. CDATA is for actual code, like in a script tag, afaik.
By the way, sorry, the code in your comment is messed up, I have to fix this sometime.
Nice