Adding Semantic Meaning to Styled Code Blocks with Code Tags
In this second part of a series, you will learn not only how to make your online code snippets look more professional and readable by using a few simple CSS styles, but how to semantically reflect their inclusion in a web page via a couple of <code> tags. This is a remarkable breakthrough that leads to writing standard-compliant markup.
Adding Semantic Meaning to Styled Code Blocks with Code Tags (Page 1 of 4 )
As with many other facets of modern web design, providing online code blocks with an appealing and readable look is something that can be achieved through different approaches. These range from using server and client-side syntax highlighters, to working solely with CSS. For obvious reasons, the former should be used with websites that need to display code snippets that use different languages, just like our own Developer Shed network, to cite an illustrative example.
While it’s fair to admit that they haven’t the flexibility of a full-featured syntax highlighter, the truth is that style sheets can be of great help in improving the visual presentation of code snippets on web pages. What’s more, when cleverly used, a simple combination of HTML tags, such and <pre> and <code> along with a few basic styles can yield impressive results -- without having to deal with additional JavaScript dependencies or third-party CSS files.
To illustrate how easy it is to polish the visual appearance of code blocks with CSS, in the part that preceded this one I created a trivial web page which contained the definition of a PHP class that I wrote down some time ago. Having this sample class neatly accommodated within the structure of the web page, turning it into an engaging and readable piece of code was only a matter of wrapping it with a couple of <pre> tags and then adding some slim borders and a clean background color. It was that simple.
It’s fair to say, however, that each time a code snippet is included in a web page, aside from making it look elegant and improving its readability, it must be also reflected semantically. Naturally, the question that comes up here is: how can this be done? Well, HTML provides the <code> tag, which permits you to add semantic meaning to a piece of code with only minor hassles. Given the importance that true semantic (X)HTML documents have at the present time, in the lines to come I’m going to enhance the example developed in the previous article by adding to it a pair of <code> elements.
Are you ready to learn the full details of this enhancement process? Then let’s get started!