Form Input Field Markup and Layout

In this lesson, we will Iearn how form fields are structured in HTML.

Linking labels and input fields through id attributes

When creating a form field, two HTML elements have to be linked:

  • an <input> field
  • and a <label>

Most software developers know that linking the two HTML elements can be performed by giving the label a for attribute, and giving an id attribute for the corresponding input field:

<label for="name-field">Name</label>
<input type="text" id="name-field" name="name" /> 

Whenever this link is established, clicking the label focuses on the input field. Without this link, the functionality of the form is compromised.

While most developers use the above method to link a label and an input field, some disadvantages may require us to consider an alternative.

The main problem is that the id attribute of a node should be a unique resource in a document. While creating a small website, using global resources is fine. In complex web applications, we never know if another module inside the application uses the same id attribute.

Linking labels and input fields through nesting

There is another method to link a <label> and an <input> field. This method is rarely used and it is less widely known. According to the HTML specification, encapsulating an <input> field in a <label> links them:

<label>
  Name
  <input type="text" name="name" />
</label>

We will use the latter method.

When using Flexbox, we can also use an encapsulating <div> element to position our input fields. Each label-input field pair will be a Flex item in a Flexbox.

The final markup of an input field:

<div class="form-flex-item">
  <label class="form-label">
    Name
    <input 
      type="text" 
      name="name" 
      class="form-input" />
  </label>
</div>

Regarding styling, we will follow modern web design trends present in most CSS frameworks and component libraries. Both Bootstrap and Material UI put the label above the corresponding input field when we focus on the input field.

Side note: Material UI puts the label inside the frame of the input field. While this solution can be implemented in CSS, we will stick to a more basic implementation of putting the label on top of the input field:

.form-label {
  margin: 20px;
  display: block;
  font-size: 14px;
  line-height: 24px;
}

.form-input {
  display: block;
  padding: 6px;
}

Get hands-on with 1200+ tech skills courses.