Form Layouts With CSS

Lay­ing out forms with Cas­cad­ing Style Sheets (CSS) is a com­plex topic. In light of many devel­op­ers doing their first over­all CSS lay­outs they often bail when it comes to lay­ing out forms with CSS and avoid­ing both tables and line breaks. The code exam­ple shows the following:

  1. Well-formed, seman­tic markup
  2. CSS for lay­out and presentation
  3. Ensure that the form is both usable (easy to read/use) and presentable
  4. No tables or line breaks

To avoid the line breaks we sim­ply use the CSS “clear” prop­erty. This prop­erty says: “clear all floated ele­ments to the x side of me”. So for clear: left; means that there should be no floated ele­ments to the left of the ele­ment, and I use this in lay­ing out the form.

Here is the CSS, but be sure to check out the full exam­ple.


body {
font: 13px "Myriad Pro", serif;
}
fieldset {
width: 300px;
padding: 10px;
}
legend {
font-weight: bold;
}
label, select, textarea, input {
float: left;
font: inherit;
border: 1px solid #ccc;
margin-bottom: 15px;
}
fieldset *:hover, fieldset *:focus {
background-color: #eee;
}
label:hover, legend:hover {
background-color: transparent;
}
label {
width: 75px;
clear: left;
font-weight: bold;
border: none;
}
input[type="submit"] {
clear: left;
margin-top: 10px;
margin-left: 75px;
}
textarea {
width: 200px;
height: 75px;
}

6 Comments

  1. I havent been both­er­ing with tabindex recently, is that some­thing we should all be adding ?

    Ayush Saran on 03.21.08
  2. @Ayush: It’s not some­thing I add per­son­ally. If I do want to pro­vide that kind of usabil­ity func­tion­al­ity I set the first form ele­ment to be the focus on page load with JS.

    Chris Poteet on 03.21.08
  3. Nice post, helps an aspir­ing CSS guy like me learn the bet­ter way to do things.

    Justin Kohnen on 04.10.08
  4. @Justin: Thanks! I’d say you’re past the “aspir­ing” part tough ;)

    Chris Poteet on 04.11.08
  5. nice use of css but input[type=“submit”] doesn’t work in ie6 so in a lot of cases this isn’t practical

    Andy on 08.13.08
  6. @Andy: You’re cor­rect, but I’ve dropped IE6 sup­port. I’m fed up of being fed up.

    Chris Poteet on 08.13.08

Got Something to Say?

(Required)
(Required)