Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > HTML/XHTML

📄 Contents

  1. Design Guidelines
  2. Coding Style Guidelines
Like this article? We recommend

Like this article? We recommend

Coding Style Guidelines

Consistency is absolutely a prerequisite for maximizing maintainability and reusability. These general guidelines for coding style can form the basis of a set of standards that will help ensure that all developers in a project—or, better, in all projects across an organization—write code consistently.

  • Use well-formed HTML.
  • Pick good names and ID values.
  • Indent consistently.
  • Limit line length.
  • Standardize character case.
  • Use comments judiciously.

Use Well-formed HTML

Although Web browsers are generally forgiving and can ignore many mistakes, rendering most HTML as the document author intended, it is still a good idea to use well-formed HTML code, for a number of reasons.

Well-formed markup code is a concept that has gained importance with increased implementation of XML. While browsers did not, in general, enforce HTML language rules very closely, XML parsers do. Code is considered well formed when it is structured according to the rules for XML 1.0. These rules relate to character case, tags, nesting, and attribute values.

In general, when most browsers encounter an unrecognized or extraneous tag, they ignore them. However, different browsers might deliver results in different—and unpredictable—ways. In addition, future versions of browsers might adhere to standards more closely than do current versions. Finally, code that includes such elements can be harder to read and understand, making maintenance more difficult.

  • Lowercase names—To be well-formed, element and attribute names must be in all lower case. In versions through 4.01, HTML is not case-sensitive. However, XML is case-sensitive, and it follows that the XHTML 1.0 recommendation is also case-sensitive. So, to ensure that code keeps working and to maximize reusability, this must be planned for.

  • Closing tags—All nonempty elements must have corresponding closing tags. Empty elements—those previously signified with a single tag, such as <hr> and <br>—must be followed immediately by a corresponding closing tag, or the tag must end with "/". For example, <hr></hr> and <hr/> are both examples of well-formed code.

  • Nested elements—All nested attributes must be properly nested—for example:

    <center><b>Some text</b></center> 

    Note that the <b> tag and its corresponding closing tag, </b>, are both nested inside the <center> and </center> tags.

    If elements overlap, then they are not properly nested, as illustrated in the following code:

    <center><b>Some text</center></b>

    While many browsers have accepted overlapping elements and given the expected results, they have always been, strictly speaking, illegal in HTML, and future versions of browsers might not support them.

  • Attribute values—Attribute values, even numeric attributes should be quoted—for example:

    <input name="txtName" type="text" size="1">
  • Code validation: Another step toward improving HTML code is to validate it against a formal published grammar and to declare this validation at the beginning of the HTML document. For example, the following line declares validation against the public HTML 3.2 Final grammar:

    <!doctype html public "-//W3C//DTD HTML 3.2 Final//EN">

    A list of formal published grammars is available from the W3C at The W3C also has a public HTML validation service at

Pick Good Names and ID Values

Use a consistent scheme for assigning the value of name and ID properties. They should be as short as reasonably possible, but without giving up descriptive power. Also, use mixed-case property values to help readability (see Listing 2). In this code snippet, the check box names express not only what the purpose of the element is, but also information about the element's type. The code also illustrates the use of mixed case to help readability.

Listing 2: Example of Good Element Names

 <b>Member? </b><input type="Checkbox" name="cbIsMember"><br>
 <b>Admin? </b><input type="Checkbox" name="cbIsAdministrator"><br>
 <b>Owner? </b><input type="Checkbox" name="cbIsOwner"><br>

HTML primarily refers to elements by their name property, while DHTML and client-side scripts use the ID property. Although DHTML documents IDs must be unique in the document, in general, there is no reason not to use the same value for an element's name and ID properties. Using the same value for these properties can reduce confusion that might arise when mixing HTML and client-side scripting.

Indent Consistently

Use indentation consistently to enhance the readability of the code. When elements carry over more than one line of code, indent the contents of elements between the start tag and the end tag. This will make it easy to see where the element begins and ends. Also, use indentation to align code at attribute names (see Listing 3).

It is a good idea to use no more than two to four spaces for each level in indentation, so as not to use up all the available line length in indentation. If possible, set up the development tool to convert tabs to spaces so that the indentation will be the same when the source is viewed in different editors or as printed output.

Listing 3: Indent Code Consistently

<table width="80%">
   <form name="frmLogin"
    <b>Login: </b><input name="txtLogin"
    <b>Password:</b><input name="txtPwd"
    <input type="Submit" value="Login">
  <td align="center" valign="top">
   <p>To log into the system, enter your user 
     name and password in the text boxes. Then 
     click the "Login" button.

Limit Line Length

Break up lines when they run too long. It is much easier to read and understand code when you can see the entire line at once. When lines of code are so long that the reader must scroll right and left to read them, it requires much more cognitive effort to understand what the code is doing. Alternatively, in some applications, long lines might wrap to the next line at the nearest word break. In either case, source code is much easier to read and understand if the developer takes explicit control of line length.

HTML is not sensitive to line breaks, so the developer can break lines at will between keywords for readability. For example, Listing 4 illustrates a code snippet in which two elements have word-wrapped to the next line because they were two long for the editor window.

Listing 4: HTML Source Code with Uncontrolled Line Breaks

<td valign="Center">
 <input type="Text" Length="45" name="txtName" language=
"JavaScript" onclick="return NameValid();"><br>
 <input type="Text" Length="35" name="txtAddress" 
language="JavaScript" onclick="return AddrValid();">

Compare this with Listing 5, where the developer took explicit control of line length. Here the code is much easier to read because the developer used line breaks and indenting to visually organize the source code.

Listing 5: HTML Source Code with Explicit Line Breaks

<td valign="Center">
 <input type="Text" Length="45" 
     onclick="return NameValid();"><br>
 <input type="Text" Length="35" 
     onclick="return AddrValid();">

Keep the limitations of printed output in mind as well. Lines longer than 80 characters will often wrap in printed output without consideration for word breaks, making source code very difficult to read.

Standardize Character Case

Source code is easier to read if the developer has applied a consistent set of rules for the use of character case—for example, the use of lower case exclusively for HTML tags. When scanning source code, the reader can unconsciously apply a visual filter, focusing attention on the HTML keywords.

The approach taken in code that appears in this article is to use all lowercase letters for HTML tags and the names of its attributes, while using mixed case and a modified form of Hungarian Notation for some attribute values (see the sidebar entitled "Hungarian Notation").

Hungarian Notation

Hungarian Notation is a convention for naming identifiers that adds a prefix to the name to provide information about the type and scope of the identifier. Dr. Charles Simonyi, a Microsoft Chief Architect at the time, introduced Hungarian Notation in the early 1980's. Long an internal Microsoft standard, variants of the convention have been widely adopted outside of Microsoft as well.

As an example of a simplified Hungarian Notation scheme, variables that contain a string could be prefixed with the character s, and a variable with global scope could be indicated with a g prefix. In this case, then, the variables sTemp and gsName in source code would be immediately identifiable as string variables with local and global scope, respectively.

In general, HTML is not a typed language, and Hungarian Notation plays a more important role in other types of Web development. However, in some cases it can add to readability. For example, the names or IDs of form elements are likely candidates for a modified form of Hungarian Notation. The prefix "btn" or "cmd" might be used for an input button. Text boxes might be prefixed with "txt," and check boxes might be prefixed with "chk" or "cb."

Use Comments Judiciously

Good comments can be invaluable for understanding and maintaining code. However, the unique nature of HTML introduces a trade-off between the value of thorough comments and the efficiency of the Web application.

The Web server reads in the HTML code and sends it as a stream of text over the network to the browser. Only after arriving at the client does the browser parse and interpret the HTML code, displaying the visible elements and ignoring the comments. The obvious implication is that the comments add nothing to the document as the browser displays it, yet they add to the processing overhead on both the server and client computers, and they increase the amount of data transferred. With almost 50 percent comments, Listing 6 illustrates what is probably excessively commented code.

Listing 6: Heavily Commented HTML Code

<!-- Form for input of security groups -->
<form name="Form1" action="https://">
 <!-- Is user a member? -->
  <b>Member? </b><input type="Checkbox" name="CB1"><br>
 <!-- Is user an administrator? -->
  <b>Admin? </b><input type="Checkbox" name="CB2"><br>
 <!-- Is user an owner? -->
  <b>Owner? </b><input type="Checkbox" name="CB3"><br>
 <!-- Send form contents to input.asp -->
   <input type="Submit" Value="Submit"> &nbsp;
 <!-- Clear the current form contents -->
   <input type="Reset" Value="Clear">

The trick is to find an appropriate level of commenting that balances these two issues. It is a good idea to comment the major logical flow and document sections to help readers quickly gain an overview of the code. Also comment dependencies and assumptions. Consistently following the other design and coding guidelines as suggested in this article—especially the ones related to naming and metadata—will help create self-documenting code.

Listing 7 illustrates how fewer comment lines and more descriptive element names can combine to provide effective documentation with a lot less overhead.

Listing 7: Lightly Commented HTML Code

<!-- Form for input of security groups -->
<form name="frmSecurityGroups"
 <b>Member? </b><input type="Checkbox" name="cbIsMember"><br>
 <b>Admin? </b><input type="Checkbox" name="cbIsAdministrator"><br>
 <b>Owner? </b><input type="Checkbox" name="cbIsOwner"><br>


This article concludes our introduction to HTML with a presentation of some valuable guidelines for working with HTML documents and code that will help maximize their maintainability and reusability. Of central importance is the need to understand HTML and its role in Web applications, to plan ahead for maintainable and reusable code, and to adopt a consistent policy on coding style.

The next article in this series kicks off our exploration of Cascading Style Sheets, a method for specifying and encapsulating display rules that can be used to modify the appearance and behavior of the Web page elements.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive:

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020