A little CSS trick

This week, I've been writing a document which contained some snippets of HTML. Now, normally when you whant to display HTML in an HTML file, you get into all sorts of bother using &lt; and &gt; for the < and > signs respectively. Not ot mention that because it is not rendered, it is more difficult to read.

So, I came up with some CSS styles which not only help with the < and >, but also coloured the HTML too. Thus:

<style>
.tag {
    color: green;
    font-weight: bold;
}
.tag:before {
    content: "<";
    color: black;
    font-weight: normal;
}
</style>

<span class="tag">img src="images/logo.gif"/></span>
This displays as:

<img src="images/logo.gif"/>

The use of the tag class is fairly obvious (assuming you know a little CSS). However, the next definition is more interesting. What this does is enable us to insert content before any content to which the style is applied. In this case, an opening <.

I then extended this concept to be a little more useful:

<style>
.endtag {
    color: green;
    font-weight: bold;
}
.endtag:before {
    content: "</";
    color: black;
    font-weight: normal;
}
.endtag:after {
    content: ">";
    color: black;
    font-weight: normal;
}
</style>

<span class="endtag">html</span>
This would display as:

</html>

So, as you can see, we've coloured just the tag name and displayed it in bold, but without having to put in the leading and trailing angle braces as this is done automagically by the CSS.

The astute readers amongst you will have noticed that I set the colour to black and the font weight to normal in the "before" and "after" pseudo-styles. That is because these styles are applied after their parent, so without that change the angle bracket would be bold and green.

I extended the use of this to wrap attribute values in double quotes and colour them and also handle empty tags - eg <table>. It made the document a whole lot more readable.

Note to readers: do not attempt to do this in StarOffice 1.x as StarOffice strips all of the embedded style directives out of your HTML and attempts to apply the style changes in line. It just ruins the whole thing, so I ended up using trusty vi for editing it :)

Comments:

Post a Comment:
Comments are closed for this entry.
About

tdw

Search

Top Tags
Archives
« July 2014
MonTueWedThuFriSatSun
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
   
       
Today