MDN self-hosted library · e01.org

Styling web forms

Learnwebdevelopment/Extensions/Forms/Advancedformstyling

Learn_web_development/Extensions/Forms/Advanced_form_styling

In the previous few articles, we showed how to create web forms in HTML. Now, we'll show how to style them in CSS.

Prerequisites: A basic understanding of HTML and CSS Styling basics.
Objective: To understand the issues behind styling forms, and learn some of the basic styling techniques that will be useful to you.

Challenges in styling form widgets

History

In 1995, the HTML 2 specification introduced form controls (a.k.a. "form widgets", or "form elements"). But CSS wasn't released until late 1996, and wasn't supported by most browsers until years afterward; so, in the interim, browsers relied on the underlying operating system to render form widgets.

Even with CSS available, browser vendors were reluctant at first to make form elements stylable, because users were so accustomed to the looks of their respective browsers. But things have changed, and forms widgets are now mostly stylable, with a few exceptions.

Types of widgets

Easy-to-style

  1. form
  2. fieldset and legend
  3. Single-line text inputs (e.g., type text, url, email), except for <input type="search">.
  4. Multi-line textarea
  5. Buttons (both input and button)
  6. label
  7. output

Harder-to-style

The article Advanced form styling shows how to style these.

Having internals can't be styled in CSS alone

  • <input type="color">
  • Date-related controls such as <input type="datetime-local">
  • <input type="range">
  • <input type="file">

    [!NOTE] The button that opens the file picker can be styled with ::file-selector-button. The text beside it, which names the selected file, cannot.

  • Elements involved in creating dropdown widgets, including select, option, optgroup and datalist.

    [!NOTE] Some browsers now support Customizable select elements, a set of HTML and CSS features that together enable full customization of <select> elements and their contents just like any regular DOM elements.

  • progress and meter

For example, the date picker calendar, and the button on \

  • What is your favorite meal?
    
    ```css hidden live-sample___positioned-legend
    form {
      width: 500px;
      margin: 0 auto;
    }
    
    fieldset {
      position: relative;
      margin-bottom: 20px;
    }
    
    legend {
      position: absolute;
      color: white;
      background-color: black;
      padding: 3px;
      bottom: 0;
      right: 0;
    }
    

    100%

    To position the legend in this manner, we used the following CSS (other declarations removed for brevity):

    fieldset {
      position: relative;
    }
    
    legend {
      position: absolute;
      bottom: 0;
      right: 0;
    }
    

    The <fieldset> needs to be positioned too, so that the <legend> is positioned relative to it (otherwise the <legend> would be positioned relative to the <body>).

    The legend element is very important for accessibility — it will be spoken by assistive technologies as part of the label of each form element inside the fieldset — but using a technique like the one above is fine. The legend contents will still be spoken in the same way; it is just the visual position that has changed.

    [!NOTE] You could also use the transform property to help you with positioning your <legend>. However, when you position it with for example a transform: translateY();, it moves but leaves an ugly gap in the <fieldset> border, which is not easy to get rid of.

    A specific styling example

    Let's look at a concrete example of how to style an HTML form. We will build a fancy-looking "postcard" contact form; see here for the finished version.

    If you want to follow along with this example, make a local copy of our postcard-start.html file, and follow the below instructions.

    The HTML

    The HTML is only slightly more involved than the example we used in Your first form; it just has a few extra IDs and a heading.

    <form>
      <h1>to: Mozilla</h1>
    
      <div id="from">
        <label for="name">from:</label>
        <input type="text" id="name" name="user_name" />
      </div>
    
      <div id="reply">
        <label for="mail">reply:</label>
        <input type="email" id="mail" name="user_email" />
      </div>
    
      <div id="message">
        <label for="msg">Your message:</label>
        <textarea id="msg" name="user_message"></textarea>
      </div>
    
      <div class="button">
        <button type="submit">Send your message</button>
      </div>
    </form>
    

    Add the above code into the body of your HTML.

    Organizing your assets

    This is where the fun begins! Before we start coding, we need three additional assets:

    1. The postcard background — download this image and save it in the same directory as your working HTML file.
    2. A typewriter font: The "Veteran Typewriter" font from dafont.com — download the ZIP file, extract it, and copy the TTF file into the same directory as above.
    3. A hand-drawn font: The "Journal" font from dafont.com — download the ZIP file, extract it, and copy the TTF file into the same directory as above.

    Your fonts need some more processing before you start:

    1. Go to the Transfonter Webfont generator.
    2. Press the "Add fonts" button and upload both your TTF files.
    3. Once they are uploaded, press the "Convert" button to generate a webfont kit.
    4. Download the kit to your computer using the "Download" link.
    5. Unzip the provided zip file.
    6. Inside the unzipped contents you will find some font files (at the time of writing, two .woff files and two .woff2 files; they might vary in the future.) Copy these files into a directory called fonts inside the same directory as before. We are using two different files for each font to maximize browser compatibility; see our Web fonts article for a lot more information.

    The CSS

    Now we can dig into the CSS for the example. Add all the code blocks shown below inside the provided style element, one after another.

    Overall layout

    First, we prepare by defining our @font-face rules, and all the basic styles set on the body and form elements.

    Find the @font-face blocks inside your downloaded webfont kit, in the stylesheet.css file and replace the below @font-face blocks with them. Update the paths to the font files, and make sure the Journal and Veteran Typewriter font-family names are set to handwriting and typewriter, respectively. Your Transfonter output may be slightly different from ours, but that's OK, as long as you make the requested changes.

    @font-face {
      font-family: "handwriting";
      src:
        url("fonts/Journal.woff2") format("woff2"),
        url("fonts/Journal.woff") format("woff");
      font-weight: normal;
      font-style: normal;
      font-display: swap;
    }
    
    @font-face {
      font-family: "typewriter";
      src:
        url("fonts/VeteranTypewriter.woff2") format("woff2"),
        url("fonts/VeteranTypewriter.woff") format("woff");
      font-weight: normal;
      font-style: normal;
      font-display: swap;
    }
    
    body {
      font: 1.3rem sans-serif;
      padding: 0.5em;
      margin: 0;
      background: #222222;
    }
    
    form {
      position: relative;
      width: 740px;
      height: 498px;
      margin: 0 auto;
      padding: 1em;
      box-sizing: border-box;
      background: white url("background.jpg");
    
      /* we create our grid */
      display: grid;
      gap: 20px;
      grid-template-columns: repeat(2, 1fr);
      grid-template-rows: 10em 1em 1em 1em;
    }
    

    Notice that we've used some CSS grid and Flexbox to lay out the form. Using this we can easily position our elements, including the title and all the form elements:

    h1 {
      font:
        1em "typewriter",
        monospace;
      align-self: end;
    }
    
    #message {
      grid-row: 1 / 5;
    }
    
    #from,
    #reply {
      display: flex;
    }
    

    Labels and controls

    Now we can start working on the form elements themselves. First, let's ensure that the labels are given the right font:

    label {
      font:
        0.8em "typewriter",
        sans-serif;
    }
    

    The text fields require some common rules. In other words, we remove their borders and backgrounds, and redefine their padding and margin:

    input,
    textarea {
      font:
        1.4em/1.5em "handwriting",
        cursive,
        sans-serif;
      border: none;
      padding: 0 10px;
      margin: 0;
      width: 80%;
      background: none;
    }
    

    When one of these fields gains focus, we highlight them with a light gray, transparent, background (it is always important to have focus style, for usability and keyboard accessibility):

    input:focus,
    textarea:focus {
      background: rgb(0 0 0 / 10%);
      border-radius: 5px;
    }
    

    Now that our text fields are complete, we need to adjust the display of the single and multiple-line text fields to match, since they won't typically look the same using the defaults.

    Tweaking the text areas

    textarea elements default to being rendered as an inline-block element. The two important things here are the resize and overflow properties. While our design is a fixed-size design, and we could use the resize property to prevent users from resizing our multi-line text field, it is best to not prevent users from resizing a textarea if they so choose. The overflow property is used to make the field render more consistently across browsers. Some browsers default to the value auto, while some default to the value scroll. In our case, it's better to be sure everyone will use auto:

    textarea {
      display: block;
    
      padding: 10px;
      margin: 10px 0 0 -10px;
      width: 100%;
      height: 90%;
    
      border-right: 1px solid;
    
      /* resize  : none; */
      overflow: auto;
    }
    

    Styling the submit button

    The button element is really convenient to style with CSS; you can do whatever you want, even using pseudo-elements:

    button {
      padding: 5px;
      font: bold 0.6em sans-serif;
      border: 2px solid #333333;
      border-radius: 5px;
      background: none;
      cursor: pointer;
      transform: rotate(-1.5deg);
    }
    
    button::after {
      content: " >>>";
    }
    
    button:hover,
    button:focus {
      background: black;
      color: white;
    }
    

    The final result

    And voilà! Your form should now look something like this:

    The final look and layout of the form after applying all styling and tweaking to it as described above

    [!NOTE] If your example does not work quite as you expected and you want to check it against our version, you can find it on GitHub — see it running live (also see the source code).

    Summary

    As you can see, as long as we want to build forms with just text fields and buttons, it's easy to style them using CSS. In the next article, we will see how to handle form widgets which fall into the "bad" and "ugly" categories.

    Learn_web_development/Extensions/Forms/Advanced_form_styling