Styling HTML forms

Czytasz angielską wersję tego artykułu, ponieważ nie ma jeszcze tłumaczenia dla tego języka. Pomóż nam przetłumaczyć ten artykuł!

In this article, the user will learn how to use CSS with HTML forms to make them (hopefully) more beautiful. This can be a little bit tricky, as hilghted in the previous article. Historically, and for technical reasons, form widgets didn't mesh well with CSS. Because of those difficulties, many developers have chosen to build their own HTML widgets to gain control over their look and feel. With modern, evergreen browsers, web designers do have increasing control over the design of form elements. Let's dig in.

Why has styling form widgets been challenging?

Form controls were added to HTML in the HTML 2 specification in 1995. Before CSS. Browsers relied on the underlying operating system to manage and render them. Later, with earlier versions of CSS, using native widgets to implement form controls didn't just continue to be a technical necessity, it continued to be a style requirement. Because users are accustomed to the visual appearance of their respective platforms, browser vendors have historically been reluctant to make form controls stylable. But they've caved.

For some form widgets, it is still difficult to rebuild controls to make them stylable.  CSS continues to evolve, and browser vendors continue to improve support of CSS for form elements. We can now use CSS to style HTML forms, though we do need to take extra care to ensure we don't break usuability.

Not all widgets are created equal when CSS is involved

At present, some difficulties remain when using CSS with forms. These problems can be divided in three categories:

The good

Some elements can be styled with few if any problems across platforms. These include the following structural elements:

  1. <form>
  2. <fieldset>
  3. <label>
  4. <output>

This also includes all text field widgets (both single-line and multi-line), and buttons.

The bad

Some elements are more difficult to style, requiring more complex CSS and even some complicated tricks.

Checkboxes and radio buttons can't be styled directly, however, though there are tricks work around this. The <legend> element cannot be positioned properly across all platforms.

We describe how to handle these more specific cases in the article Advanced styling for HTML forms.

The ugly

Some elements simply can't be styled using CSS. These include: all advanced user interface widgets, such as color or date controls; pretty much the range control; and all the dropdown widgets, including <select>, <option>, <optgroup> and <datalist> elements. The range input type is notoriously difficult to style, but it is possible. The <progress> and <meter> elements have limited styability, and risk losing the visual cues that make them relevant when styled. The file picker widget is also known not to be stylable cross browser.

The main issue with all these widgets, comes from the fact that they have a very complex structure, and CSS is not currently expressive enough to style all the subtle parts of those widgets. If you want to customize those widgets, you have to rely on JavaScript to build a DOM tree you'll be able to style at the shadow DOM level. We explore how to do this in the article How to build custom form widgets. You can also use the appearance property to obliterate the native UI features or target the shadow DOM of browser specific pseudo-elements, like ::-moz-range-track.

Basic styling

To style form controls that are easy to style with CSS, you shouldn't face much if any difficulties, since they mostly behave like any other HTML element. However, the user-agent style sheet of every browser can be a little inconsistent, so there are a few tricks that can help you style them in an easier way.

Search fields & appearance: none;

Search boxes look and behave differently in different browsers. On WebKit based browsers a delete icon appears in the input box if any text is entered. It disappears when the input loses focus in Edge and Chrome, but stays in Safari. Clicking on the icon deletes the text that was entered. Firefox doesn't have the delete icon. (Some devices with dynamic keyboard also show a search icon instead of the 'next' key shown when completing other inputs.) Firefox doesn't have this icon. In Safari, the search box also has rounded corners, while other input boxes don't.

<form> 
   <input type="search"> 
</form>

With appearance: none, the default styling disappears, which means the checkbox and radio buttons disappear in some browsers
Default search input in Safari 13, Chrome 77, and Firefox 71.

To make the search the same across all browsers, we can include the appearance property. We discuss this property further in the article: Advanced styling for HTML forms.

Example

<form action="search.html" method="get">
  <p>
    <label for="search3">search: </label>
    <input id="search3" name="search3" type="search" />
  </p>
  <p>
    <label for="text">text: </label>
    <input id="text" name="text" type="text" />
  </p>
  <p>
    <label for="date">date: </label>
    <input id="date" name="date" type="date" />
  </p>
  <p>
    <label for="radio">radio: </label>
    <input id="radio" name="radio" type="radio" />
  </p>
  <p>
    <label for="checkbox">checkbox: </label>
    <input id="checkbox" name="checkbox" type="checkbox" />
  </p>
  <p><input type="submit" value="submit" /></p>
  <p><input type="button" value="button" /></p>
</form>

We can remove default styling from most input types with a single line of CSS:

input {
  -webkit-appearance: none; 
  appearance: none;
}

With appearance: none, the default styling disappears, which means the checkbox and radio buttons disappear in some browsers

Various input types in Chrome 77 with and without appearance: none set

As you can see on this screenshot of the search, text and date fields on Chrome, setting appearance: none removes stylized border, but not functionality. By impacting the look and feel, though, we've made the checkbox and radio buttons completely disappear.  Be careful when styling form controls!

Fonts and text

CSS font and text features can be used easily with any widget (and yes, you can use @font-face with form widgets). However, browsers' behaviors are often inconsistent. By default, some widgets do not inherit font-family and font-size from their parents. Many browsers use the system default appearance instead. To make your forms' appearance consistent with the rest of your content, you can add the following rules to your stylesheet:

button, input, select, textarea {
  font-family : inherit;
  font-size   : 100%;
}

The screenshot below shows the difference; on the left is the default rendering of the element in Chrome on Mac OS X, with the platform's default font style in use. On the right are the same elements, with our font harmonization style rules applied.

Form controls with default and inherited font families. By default, some types are serif and others are sans serif. Inheriting should change the fonts of all to the parent's font family - in this case a paragraph. Oddly, input of type submit does not inherit from the parent paragraph.

Form controls in Chrome 77 with default styles and font-family: inherit;

Above are a text input, date input, <select>, <textarea>, submit input and a button. On the left we have the default styling. On the right, font-family: inherit; was added along with height: 100%;.  By default, some types were serif and others were sans serif. Inheriting should change the fonts of all to the parent's font family - in this case the default serif font of the parent paragraph. They all do, with an exception: oddly, input of type=submit does not inherit from the parent paragraph in Chrome. Rather, it uses the font-family: system-ui,

There's a lot of debate as to whether forms look better using the system default styles, or customized styles designed to match your content. This decision is yours to make, as the designer of your site, or Web application. Just realize, there are some differences.

Box model

All text fields have complete support for every property related to the CSS box model (width, height, padding, margin, and border). As before, however, browsers rely on the system default styles when displaying these widgets. It's up to you to define how you wish to blend them into your content. If you want to keep the native look and feel of the widgets, you'll face a little difficulty if you want to give them a consistent size.

This is because each widget has their own rules for border, padding and margin. So if you want to give the same size to several different widgets, you have to use the box-sizing property:

input, textarea, select, button {
  width : 150px;
  margin: 0;
  box-sizing: border-box;
}

box model properties effect most input types.

Form controls in Firefox 71 with default styles and box-model properties applied

In the screenshot above, the left column is built without box-sizing, while the right column uses this property with the value border-box and a defined width of 150px. We have a radio button, checkbox, range, text input, date input, <select>, <textarea>, input of type submit and a <button>. Notice how this lets us ensure that all of the elements occupy the same amount of space, despite the platform's default rules for each kind of widget.

What may not be apparent via the screen shot, is that the radio and checkbox controls still look the same, but they are centered in the 150px of horizontal space provided by the width property. Other browsers may not center the widgets, but they do adhere to the space allotted.

Positioning

Positioning of HTML form widgets is generally not a problem; however, there are two elements you should take special note of:

legend

The <legend> element is okay to style, except for positioning. In every browser, the <legend> element is positioned on top of the top border of its <fieldset> parent. There is absolutely no way to change it to be positioned within the HTML flow, away from the top border. You can, however, position it absolutely or relatively, using the position property. But otherwise it is part of the fieldset border.

Because the <legend> element is very important for accessibility reasons, it will be spoken by assistive technologies as part of the label of each form element inside the fieldset, it's quite often paired with a title, and then hidden in an accessible way. For example:

HTML
<fieldset>
  <legend>Buttons</legend>
  <button type="button">Save</button>
  <button type="submit">Send the form!</button>
</fieldset>
CSS
legend {
  width: 1px;
  height: 1px;
  overflow: hidden;
  position: absolute;
}

By adding the position absolute, it takes the legend out of the page flow, and therefore out of the top border of the fieldset.

textarea

By default, all browsers consider the <textarea> element to be an inline block, aligned to the text bottom line. This is rarely what we actually want to see. To change from inline-block to block, it's pretty easy to use the display property. But if you want to use it inline, it's common to change the vertical alignment:

textarea {
  vertical-align: top;
}

Example

Let's look at a concrete example of how to style an HTML form. This will help make a lot of these ideas clearer. We will build the following "postcard" contact form:

This is what we want to achieve with HTML and CSS

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 the first article of this guide; it just has a few extra IDs and a title.

<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 "Secret Typewriter" font from fontsquirrel.com — download the TTF file into the same directory as above.
  3. A handdrawn font: The "Journal" font from fontsquirrel.com — download the TTF file into the same directory as above.

Your fonts need some more processing before you start:

  1. Go to the fontsquirrel Webfont Generator.
  2. Using the form, upload both your font files and generate a webfont kit. Download the kit to your computer.
  3. Unzip the provided zip file.
  4. Inside the unzipped contents you will find two .woff files and two .woff2 files. Copy these four files into a directory called fonts, in the same directory as before. We are using two different files for each font to maximise 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 <style> element, one after another.

First, we prepare the ground by defining our @font-face rules, all the basics on the <body> element, and the <form> element:

@font-face {
    font-family: 'handwriting';
    src: url('fonts/journal-webfont.woff2') format('woff2'),
         url('fonts/journal-webfont.woff') format('woff');
    font-weight: normal;
    font-style: normal;
}

@font-face {
    font-family: 'typewriter';
    src: url('fonts/veteran_typewriter-webfont.woff2') format('woff2'),
         url('fonts/veteran_typewriter-webfont.woff') format('woff');
    font-weight: normal;
    font-style: normal;
}

body {
  font  : 21px sans-serif;
  padding : 2em;
  margin  : 0;
  background : #222;
}

form {
  position: relative;
  width  : 740px;
  height : 498px;
  margin : 0 auto;
  background: #FFF url(background.jpg);
}

Now we can position our elements, including the title and all the form elements:

h1 {
  position : absolute;
  left : 415px;
  top  : 185px;
  font : 1em "typewriter", sans-serif;
}

#from {
  position: absolute;
  left : 398px;
  top  : 235px;
}

#reply {
  position: absolute;
  left : 390px;
  top  : 285px;
}

#message {
  position: absolute;
  left : 20px;
  top  : 70px;
}

That's where we start working on the form elements themselves. First, let's ensure that the <label>s are given the right font:

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

The text fields require some common rules. Simply put, we remove their borders and backgrounds, and redefine their padding and margin:

input, textarea {
  font    : .9em/1.5em "handwriting", sans-serif;
  border  : none;
  padding : 0 10px;
  margin  : 0;
  width   : 240px;
  background: none;
}

When one of these fields gains focus, we highlight them with a light grey, transparent, background. Note that it's important to add the outline property, in order to remove the default focus highlight added by some browsers:

input:focus, textarea:focus {
  background   : rgba(0,0,0,.1);
  border-radius: 5px;
  outline      : none;
}

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.

The single-line text field needs some tweaks to render nicely in Internet Explorer. Internet Explorer does not define the height of the fields based on the natural height of the font (which is the behavior of all other browsers). To fix this, we need to add an explicit height to the field, as follows:

input {
    height: 2.5em; /* for IE */
    vertical-align: middle; /* This is optional but it makes legacy IEs look better */
}

<textarea> elements default to being rendered as a block element. The two important things here are the resize and overflow properties. Because our design is a fixed-size design, we will use the resize property to prevent users from resizing our multi-line text field. 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 every one will use auto:

textarea {
  display : block;

  padding : 10px;
  margin  : 10px 0 0 -10px;
  width   : 340px;
  height  : 360px;

  resize  : none;
  overflow: auto;
}

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

button {
  position     : absolute;
  left         : 440px;
  top          : 360px;
  padding      : 5px;
  font         : bold .6em sans-serif;
  border       : 2px solid #333;
  border-radius: 5px;
  background   : none;
  cursor       : pointer;
  transform    : rotate(-1.5deg);
}

button:after {
  content      : " >>>";
}

button:hover,
button:focus {
  outline     : none;
  background  : #000;
  color       : #FFF;
}

And voila!

Note: If your example does not work quite like 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).

Conclusion

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. If you want to know more of the little CSS tricks that can make your life easier when working with form widgets, take a look at the form part of the normalize.css project.

In the next article, we will see how to handle form widgets which fall in the "bad" and "ugly" categories.

In this module