This site will look much better in a browser that supports web standards, but it is accessible to any browser or Internet device.

John McSweeney - picture detail

John McSweeney

May 9, 2008, 10:36 pm

Website Design

Displaying Code with a CSS Class Selector

 

CSS2, provides pattern matching methods, or selectors for specifying CSS rules that match HTML elements in a web document. To display code snippets, I often make use of a Class selector.
(Note: in 2005 W3C introduced a draft for CSS3 selectors)

HTML elements have attributes, or properties. An example of this is the paragraph attribute named class. I have written the following class selector (note the use of dot notation) for displaying blocks of code within HTML tags:

.code {
  color: Navy;
  font-family: "Courier New", Courier, monospace;
  padding:0px;
  margin: 0px;
}

To display a code extract in a paragraph, for example, I make a small addition to the opening paragraph tag by writing a name/value pair for the required attribute, in this case class. That is:

<p class="code">
The code is placed here
</p>

The CSS class selector ensures that any text placed between these paragraph tags is formatted in a Navy blue Courier New font, without any padding or margins.

A class selector can be applied to any HTML element. This is extremely useful. Frequently, when writing about programming, I need to format inline content, rather than a complete block of text. For example, in the next sentence I have made reference to a Java class, which I like to format differently.

The above code makes use of the Java ServerSocket class.

I employ <span></span> tags in combination with a class selector to accomplish this. By setting the class attribute of these tags to the value code, I can format inline references to code in same way that I treat corresponding block-level content.

The HTML is written like this:

<p>The above code makes use of the Java <span class="code">ServerSocket</span> class.</p>

Next page » XHTML

Previous page « Displaying code