TJKDesign: Home Page

ez-css Putting the 'less' in table-less layouts. css-101 logo
Bookmark this article at these sites:

Using Javascript to help positioning LEGEND elements.

It is a post from Russ Weakley on the WSG list that inspired this article.

Simply put, it is not possible across browsers to position the LEGEND element in a Fieldset.
For example, Firefox will "ignore" the second rule below:

fieldset {position:relative;}
legend {position:absolute;top:-20px;left:100px}

The workaround is to use a container to wrap the content of the LEGEND element and then style that new container intead; for example , using a SPAN element:

<fieldset><legend><span>Customer Info<span></legend> ... </fieldset>

Then, the CSS rules would become:

fieldset {position:relative;}
legend span {display:block;position:absolute;top:-20px;left:100px}

The problem with this is that it works alright, but it is not "pretty". So I wrote a short script to use this "hack" while keeping the markup clean.
What the script does is that it parses the document looking for LEGEND elements and each time it finds one it wraps its content into a SPAN.

The script:

<script type="text/javascript">
function TJK_legend(){// v1.1 Copyright (c) 2006 TJKDesign - Thierry Koblentz
  if (document.getElementsByTagName && document.createElement){
	var zLegend = document.getElementsByTagName("legend");
  	for (i=0;i<zLegend.length;i++){
		var zSpan = document.createElement("span");
		var zData = document.createTextNode(zLegend[i];

How to make things work:

Cut and paste the above code into the head of your document or download (1Kb) and unzip the file into a directory within your site. Then, use a SCRIPT element to link the JS file (TJK_legend.js) to your pages within the HEAD element of your documents, as shown below:

<script type="text/javascript" src="/js/TJK_legend.js"></script>

Note: In this case, the file has been saved inside a directory called "JS" within the root folder.

Use the onload attribute of the body element to call the function; for example: <body onload="TJK_legend();"> or, better, use a technique like the one explained here: executing JavaScript on page load.

Take note If you're already using an external Javascript file, it may be a good idea to plug the content of TJK_legend.js (everything between "<!--" and "//-->") into it to avoid an extra file request.

Now when the page loads, this:

<fieldset><legend>Customer Info</legend> ... </fieldset>

Will become this:

<fieldset><legend><span>Customer Info<span></legend> ... </fieldset>

Further reading:

Legends of Style

Please use this contact form to send feedback and report errors.