Jump to main navigation


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:

  1. When the page is displayed without CSS, I'd like the code fragment to have a decent formatting.
  2. 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;
}

You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

23 comments to “How to display code fragments in web pages”

  1. #01 By South Coast CSS Wave Warrior, 080227 at 10:43

    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)

  2. #02 By dense13, 080227 at 11:22

    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. ;)

  3. #03 By South Coast CSS Wave Warrior, 080227 at 11:44

    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)

  4. #04 By natalia, 080313 at 23:53

    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..

  5. #05 By natalia, 080314 at 00:07

    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 :-/

  6. #06 By dense13, 080314 at 10:13

    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.

  7. #07 By natalia, 080314 at 19:20

    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?

  8. #08 By dense13, 080315 at 07:54

    You might be right, doing the color coding on the server side, I’ll think about it.

  9. #09 By dense13, 080401 at 15:39

    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. ;)

  10. #10 By Bill, 080620 at 13:24

    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) ;))

  11. #11 By Bill, 080620 at 13:27

    That last space should have shown "non-breaking-space characters".
    Blimey.

  12. #12 By dense13, 080620 at 15:03

    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.

  13. #13 By Bill, 080620 at 21:12

    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)...

  14. #14 By dense13, 080620 at 23:36

    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. :)

  15. #15 By Bill, 080621 at 13:03

    W H A S S A T ? ? ! !

  16. #16 By New code posting method :) « Jinto Reedwine’s Blog, 080707 at 02:44

    [...] 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 [...]

  17. #17 By yagami, 090804 at 19:11

    how do u make the comment part please help me thxs

  18. #18 By yagami, 090804 at 19:13

    How do you put this in for people to write in. E.g the comments

  19. #19 By dense13, 090811 at 22:25

    Hi yagami, I'm not sure what you mean, can you be more specific?

  20. #20 By evanwebwills, 110623 at 00:27

    Is there any other way (except <code> and [code]) to display html
    codes on the web page?

  21. #21 By hire | chrissabbatini » HOW TO: display code fragments in web pages, 110728 at 22:52

    [...] and if you have any suggestions to help me improve my method,
    please leave a comment! Resources: dense13.com Follow [...]

  22. #22 By dense13, 110909 at 23:23

    @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.

  23. #23 By George, 120822 at 03:16

    Nice

Additional content and navigation

Categories

Recent comments