cssFloat adds break


In IE7 that is.

The object of this exercise was to create an aligned form with the DOM. As usual, the form input elements should be aligned, but HTML and CSS lack the basic notation to help you in this matter so you have to resolve to advanced CSS hacks.

Now, one method of accomplishing this is to float the label and margin the input. No problem:

Code: (HTML + inline CSS)

Works fine, "username" is displayed left of the input in both IE and FF.

Now let's do this with DOM (this requires that you at least define the body tag):

Code: (Javascript)
var a = document.createElement("div");
a.style.display = 'block';
a.style.cssFloat = 'left';
a.style.width = "80px";
a.style.backgroundColor = 'red';
a.innerHTML = "Username: ";
a.htmlFor = 'user';

var b = document.createElement("input");
b.style.backgroundColor = 'blue';
b.name = 'user';
b.value = 'fox';
b.style.marginLeft = "100px";


Now look what happens. Firefox shows what you expect. Explorer does not! It added a linebreak after the div!

This seems to be unavoidable. "Hacks" like encapsulating the elements together or whatever don't seem to work. Quite annoying.

It should be obvious that using innerHTML works fine, but that's not really DOM. That's just being lazy :)

Code: (Javascript)
var s = document.createElement("span");
s.innerHTML = "value='fox' style='background-color: blue;' />";

The other solution, which allows you to use the DOM, is to create a css style rule with a float and assign it to the className property of the DOM element. I haven't tested whether it works to create the rule dynamically, but I can confirm it works when you include it in an external CSS file.

Ps. Another common method to align form fields is to use `position: absolute` on the label and `margin-left: 100px` on the input. This is IE7 DOM proof.

Hope it helps you :)