Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Practical HTML and CSS

You're reading from   Practical HTML and CSS Elevate your internet presence by creating modern and high-performance websites for the web

Arrow left icon
Product type Paperback
Published in Nov 2024
Publisher Packt
ISBN-13 9781835080917
Length 492 pages
Edition 2nd Edition
Languages
Arrow right icon
Authors (3):
Arrow left icon
Brett Jephson Brett Jephson
Author Profile Icon Brett Jephson
Brett Jephson
Lewis Coulson Lewis Coulson
Author Profile Icon Lewis Coulson
Lewis Coulson
Ana Carolina Silveira Ana Carolina Silveira
Author Profile Icon Ana Carolina Silveira
Ana Carolina Silveira
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

Preface 1. Part 1: Introducing HTML and CSS
2. Chapter 1: Introduction to HTML and CSS FREE CHAPTER 3. Chapter 2: Structure and Layout 4. Chapter 3: Text and Typography Styling 5. Part 2: Understanding Website Fundamentals
6. Chapter 4: Creating and Styling Forms 7. Chapter 5: Adding Animation to Web Pages 8. Chapter 6: Themes, Color, and Polishing Techniques 9. Part 3: Building for All
10. Chapter 7: Using CSS and HTML to Boost Performance 11. Chapter 8: Responsive Web Design and Media Queries 12. Chapter 9: Ensuring Accessibility in HTML and CSS 13. Part 4: Advanced Concepts
14. Chapter 10: SEO Essentials for Web Developers 15. Chapter 11: Preprocessors and Tooling for Efficient Development 16. Chapter 12: Strategies for Maintaining CSS Code 17. Chapter 13: The Future of HTML and CSS – Advancements and Trends 18. Index 19. Other Books You May Enjoy

Making forms accessible

Accessibility is a growing concern for websites. It is vital we make our websites as accessible as possible for all users. When working with forms in HTML, there are a few key areas in which we can improve accessibility, which we will now look at:

  • Labeling form elements
  • Grouping related form elements
  • Validating user input

Labeling form elements correctly

We have already used labels for form elements, which is one of the most crucial ways of ensuring form accessibility. Whenever you use a label element, you need to ensure you use the for attribute, as follows:

<label for="first_name">First name:</label>
<input id="first_name" type="text" name="first_name" />

This ensures that you explicitly associate a descriptive label with a form control.

Grouping related form elements

We previously grouped our form elements with the fieldset element, but there is an additional element called legend that is useful for this purpose. Grouping form elements improves accessibility by breaking down a form into smaller focused parts. It is easier for a user to understand each part of the form at a time. Using a legend element allows you to provide a description of what the purpose of the form is, grouped by a fieldset element. An example of this is shown here:

<fieldset>
  <legend>Favorite web language?</legend>
  <div>
    <input type="radio" id="html" name="html" />
    <label for="html">HTML</label>
  </div>
  <div>
    <input type="radio" id="css" name="css" />
    <label for="css">CSS</label>
  </div>
</fieldset>

The following figure shows the output for the preceding code:

Figure 4.19: A legend and fieldset form, as shown in the browser

Figure 4.19: A legend and fieldset form, as shown in the browser

Validating user input

Validating form fields is another great and easy way to improve our form’s accessibility. We improve form accessibility by helping our users avoid mistakes when inputting data into our form fields. Luckily, this is easy to achieve, using the required attribute for fields that we require user input from. This is for situations where we want to ensure that the data entered is in a certain format – for example, email addresses, website URLs, or dates. We can make use of the type attribute when using text inputs:

<label for="first_name">First name(required)</label>
<input
  type="text"
  id="first_name"
  name="first_name"
  required
/>

The following figure shows the output for the preceding code if a user tried to submit a form without entering any text into the text field:

Figure 4.20: The required attribute, as shown in the browser

Figure 4.20: The required attribute, as shown in the browser

The following shows some examples of making use of the type attribute when using text inputs in which you want user input to be for a certain format (e.g., an email address):

<label for="email">Email</label>
<input type="email" id="email" name="email" />

For a full list of the available type attributes. visit https://developer.mozilla.org/en-US/docs/Learn/Forms/HTML5_input_types.

To learn more about web accessibility, visit https://developer.mozilla.org/en-US/docs/Web/Accessibility.

Video store forms

To put our newfound knowledge into practice, we will now build two complex forms for the video store project page examples from the previous chapter, where we built a whole web page, component by component.

Exercise 4.03 – a new account signup form

In this exercise, we will write some HTML and CSS to create an account signup form. Our aim is to produce a web form like the following wireframe:

Figure 4.21: A wireframe of a new account form

Figure 4.21: A wireframe of a new account form

Note

The complete code for this exercise can be found at https://packt.link/sGtB9.

Let’s complete the exercise by following the following steps:

  1. Start by creating a new file in VS Code called signup-form.html, and use the following code as your starting point:
    <!DOCTYPE html>
    <html>
    <head>
      <title>Signup form</title>
      <style>
        body {
          font-family: arial, sans-serif;
        }
      </style>
    </head>
    <body>
      <h1>Create new account</h1>
      <form action="url_to_send_form_data" method="post">
        <fieldset>
        </fieldset>
      </form>
    </body>
    </html>
  2. Now, we will add the HTML for the form up until just before the Sign up for newsletter checkbox. Note how we have added the required attribute to the elements that we require the user to provide a value for:
    <fieldset>
      <div>
        <label for="first_name">
          First name: <span>*</span>
        </label>
        <input
          id="first_name"
          type="text"
          name="firstname"
          required
        />
      </div>
      <div>
        <label for="last_name">
          Last name: <span>*</span>
        </label>
        <input
          id="last_name"
          type="text"
          name="lastname"
          required
        />
      </div>
    </fieldset>
  3. Next, we will add the checkbox to sign up to the newsletter. In order to have the checkbox first and the description later, label comes after input:
    <fieldset>
      <div>
        <label for="first_name">
          First name: <span>*</span>
        </label>
        <input
          id="first_name"
          type="text"
          name="firstname"
          required
        />
      </div>
      <div>
        <label for="last_name">
          Last name: <span>*</span>
        </label>
        <input
          id="last_name"
          type="text"
          name="lastname"
          required
        />
      </div>
      <div class="checkbox">
        <input
          id="newsletter"
          type="checkbox"
          name="newsletter"
          value="yes"
        />
        <label for="newsletter">
          Sign up for newsletter
        </label>
      </div>
    </fieldset>
  4. Now, we will add the remaining fields and the submit button below the checkbox shown in the wireframe. Again, make sure to add the required attribute to elements that need a value to be provided:
      <div class="checkbox">
        <input
          id="newsletter"
          type="checkbox"
          name="newsletter"
          value="yes"
        />
        <label for="newsletter">
          Sign up for newsletter
        </label>
      </div>
      <div>
        <label for="email">Email: <span>*</span></label>
        <input
          id="email"
          type="email"
          name="email"
          required
        />
      </div>
      <div>
        <label for="password">
          Password: <span>*</span>
        </label>
        <input
          id="password"
          type="password"
          name="password"
          required
        />
      </div>
      <button type="submit">Create new account</button>
  5. If you look at the HTML file in your web browser, you should now have a web page that looks like the following screenshot:
Figure 4.22: An unstyled signup form in the browser

Figure 4.22: An unstyled signup form in the browser

  1. We can now add the CSS to style the form so that it more closely resembles the one shown in the preceding wireframe. We will start by applying some styles that deal with the spacing of elements and then style the red asterisks shown in the wireframe. The following code snippet will be inside the style tag, following the font style applied to the body element:
        fieldset {
          border: 0;
        }
        fieldset>div {
          margin-bottom: 30px;
        }
        label {
          display: block;
          margin-bottom: 10px;
        }
        label span {
          color: red;
        }
        input {
          padding: 10px;
          width: 200px;
        }
  2. Next, we will apply some styles to the valid and invalid states for the text inputs. Feel free to change the colors of these styles to suit your own taste:
      input:valid {
        border: 2px solid green;
      }
      input:invalid {
        border: 2px solid red;
      }
  3. Next, we will add some styling for the checkbox and the submit button, as shown in the following code. Again, feel free to adjust the colors to suit your needs:
      .checkbox input ,
      .radio input {
        float: left;
        margin-right: 10px;
        width: auto;
      }
      button {
        background: green;
        border: 0;
        color: white;
        width: 224px;
        padding: 10px;
        text-transform: uppercase;
      }

    If you now right-click on the filename in VS Code, on the left-hand side of the screen, and select open in default browser, you will see the form in your browser.

    You should now have a form that looks like the following figure:

Figure 4.23: A styled signup form in the browser

Figure 4.23: A styled signup form in the browser

  1. We will now check that the email validation works correctly for the form by adding some text to the email field that isn’t a valid email address:
Figure 4.24: A form showing an invalid email address

Figure 4.24: A form showing an invalid email address

  1. Next, we will check all of the required field validations by trying to submit the form without adding input to any of the required fields:
Figure 4.25: A form highlighting fields that need to be filled in to submit the form

Figure 4.25: A form highlighting fields that need to be filled in to submit the form

We have now completed the signup form for our video store. We will also need to create a checkout page to allow a user to complete their online purchases. The next exercise will show how you can create a checkout form.

Exercise 4.04 – a checkout form

In this exercise, we will write some HTML and CSS to create a checkout form. We will make use of all the concepts and form elements we have learned so far in the chapter. Our aim is to produce a form similar to the following figure:

Figure 4.26: A checkout form wireframe

Figure 4.26: A checkout form wireframe

Note

The complete code for this exercise can be found at https://packt.link/xvl1y.

Let’s complete the exercise by following the following steps:

  1. Start by creating a new file in VS Code called checkout-form.html, and use the following code as a starting point. This gives us the skeletal HTML and CSS we will need to get started writing the checkout form:
    <!DOCTYPE html>
    <html>
    <head>
      <title>Checkout form</title>
      <style>
        body {
          font-family: arial, sans-serif;
        }
      </style>
    </head>
    <body>
      <h1>Checkout</h1>
      <form action="url_to_send_form_data" method="post">
        <fieldset>
        </fieldset>
      </form>
    </body>
    </html>
  2. Now, we will add the HTML for the form inside fieldset up until the address field. Note how we have added the required attribute to the elements that we require the user to provide a value for:
      <h2>Shipping address</h2>
      <div class="double-input">
        <div>
          <label for="first_name">
            First name: <span>*</span>
          </label>
          <input
            id="first_name"
            type="text"
            name="firstname"
            required
          />
        </div>
        <div>
        <label for="last_name">
          Last name: <span>*</span>
        </label>
        <input
          id="last_name"
          type="text"
          name="lastname"
          required
        />
        </div>
      </div>
      <div class="single-input">
        <label for="address">
          Address: <span>*</span>
        </label>
        <input
          id="address"
          type="text"
          name="address"
          required
        />
      </div>
  3. Now, below the address field, we write the HTML and CSS for the postcode using input id and the country using select, as shown in the wireframe:
      <div class="double-input">
        <div>
          <label for="postcode">
            Postcode: <span>*</span>
          </label>
          <input
            id="postcode"
            type="text"
            name="postcode"
            required
          />
        </div>
        <div>
          <label for="country">Country:</label>
          <div class="select-wrapper">
            <select id="country">
              <option value="england">England</option>
              <option value="scotland">Scotland</option>
              <option value="ireland">Ireland</option>
              <option value="wales">Wales</option>
            </select>
          </div>
        </div>
      </div>
  4. As shown in the preceding wireframe, we will now add a level 2 header followed by the radio-type checkboxes, as shown in the following code:
      <h2>Shipping method</h2>
      <div class="radio>
        <input
          id="standard"
          type="radio"
          name="shipping-method"
          value="standard"
        />
        <label for="standard">Standard</label>
      </div>
      <div class="radio">
        <input
          id="nextday"
          type="radio"
          name="shipping-method"
          value="nextday"
        />
        <label for="nextday">Next day</label>
      </div>
      <button type="submit">Submit</button>
  5. If you look at the HTML file in your web browser, you should now have a web page that looks like the following screenshot:
Figure 4.27: An unstyled checkout form in the browser

Figure 4.27: An unstyled checkout form in the browser

  1. We can now add some CSS to style the form so that it more closely resembles the form shown in the preceding wireframe. We will start by applying some styles that deal with the spacing of elements and style the red asterisks shown in the wireframe:
      fieldset {
        border: 0;
        padding: 0;
      }
      fieldset > div {
        margin-bottom: 30px;
      }
      label {
        display: block;
        margin-bottom: 10px;
      }
      label span {
        color: red;
      }

    Note that input and select have the same style, as shown in the following code:

      input,
      select {
        border: 1px solid grey;
        padding: 10px;
        width: 200px;
      }
  2. Now, let’s add the CSS for the select boxes. We style select as shown in the following code snippet:
      select {
        background: transparent;
        border-radius: 0;
        box-shadow: none;
        color: #666;
        -webkit-appearance: none;
        width: 100%;
      }

    Complete styling select using the following code:

      .select-wrapper {
        position: relative;
        width: 222px;
      }
      .select-wrapper:after {
        content: '< >';
        color: #666;
        font-size: 14px;
        top: 8px;
        right: 0;
        transform: rotate(90deg);
        position: absolute;
        z-index: -1;
      }
  3. Finally, we will finish off the styling by adding some CSS for the inputs and the button styles, as shown in the following code:
      .single-input input {
        width: 439px;
      }
      .double-input {
        display: flex;
      }
      .double-input > div {
        margin-right: 15px;
      }
      .checkbox input {
        float: left;
        width: auto;
        margin-right: 10px;
      }

    The following code is added to style the button:

      button {
        background: green;
        border: 0;
        color: white;
        width: 224px;
        padding: 10px;
        text-transform: uppercase;
      }

    To style the inputs, we add the following code:

      input:valid {
        border: 2px solid green;
      }
      input:invalid {
        border: 2px solid red;
      }

    If you now right-click on the filename in VS Code, on the left-hand side of the screen, and select open in default browser, you will see the form in your browser.

    You should now have a form that looks like the following figure:

Figure 4.28: A styled checkout form in the browser

Figure 4.28: A styled checkout form in the browser

  1. Now, we will check whether the validation works for our required fields by submitting the form with empty fields. We will see something like the following screenshot:
Figure 4.29: A form highlighting the required fields before submitting it

Figure 4.29: A form highlighting the required fields before submitting it

Activity 4.01 – building an online property portal website form

An international online property website has approached you to design a search form for their listings page. This form should have the following fields – search radius, price range, bedrooms, property type, and added to the site – as well as an option to include sold properties in the user’s search. Create your own solution using the skills you have learned in this chapter:

  1. Start by creating a new file named form.html in VS Code.
  2. Then, start writing the HTML for the form using the description of the fields required for this form.
  3. Once you are happy with the HTML you have written, you can let your creativity run wild and style the form using CSS. Make sure that you include styling for validation:
Figure 4.30: The expected output of the activity

Figure 4.30: The expected output of the activity

Note

The solution to this activity is available on GitHub at https://packt.link/7OoUW

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime