Forms with CSS (1 of 3) – HTML Markup

When I develop web pages, I try to use web standards complaint HTML code and CSS for layout and design. This gives a lot of flexibility in the design while being usable for people using screen readers and other browsers that don’t use CSS.

This has worked fine with regular web pages, however I’ve always struggled with how to mark up forms to be semantically correct. After doing a little research on the subject, I’ve switched the way I typically write forms. I’m still learning so am open to suggestions to improve my skills.

Some of the forms I used to write would have elements that looked like:

  First Name:
  <input id="txtFirstName" name="txtFirstName" />
  Last Name:
  <input id="txtLastName" name="txtLastName" />

When I wanted the input boxes to line up vertically with each other, I’d either add the necessary spacing using “ “or build a table with labels in the first column and input fields in the second.

I’ve come to realize that there are better ways to do this markup. The way I typically do this now is:

  <label for="txtFirstName">First Name:</Label>
  <input id="txtFirstName" name="txtFirstName" />

  <label for="txtLastName">Last Name:</Label>
  <input id="txtLastName" name="txtLastName" />

This adds a little more HTML code, however provides more semantic information. Once you get used to coding the form like this, it’s pretty easy. A huge advantage of using the <fieldset> and <label> tags, you have a lot of hooks to use with your CSS. This makes it easy to format the form. More information in “Forms with CSS (2 of 3) – Styles

Note for ASP.NET programmers: The third tip in this article from Standards Schmandards shows how to tie your <label> tags to the tags that is generated from <asp:TextBox>.

Related Articles:
Forms with CSS (2 of 3) – Styles
Forms with CSS (3 of 3) – Checkboxes


1 comment so far

  1. Darren on

    This is also a great way for semantically correct markup! 😀
    Something I love.

Comments are closed.

%d bloggers like this: