Styling web forms

In the previous few articles we looked at all the HTML you'll need to create and structure your web forms. In this article we will move on to looking at how to use CSS to style your form controls. This has historically been difficult — form controls vary greatly in how easy they are to customize with CSS — but it is getting easier as old browsers are retired and modern browsers give us more features to use.

Prerequisites: Basic computer literacy, and a basic understanding of HTML and CSS .
Objective: To understand the issues behind styling forms, and learn some of the basic styling techniques that will be useful to you.

Why is styling form widgets challenging?

Form controls were added to HTML in the HTML 2 specification in 1995; CSS wasn't released until late 1996, and wasn't supported very well by browsers for a few years after that. Browsers relied on the underlying operating system to manage and render form controls.

And even with CSS available to style HTML, browser vendors have historically been reluctant to make form controls stylable because users were so accustomed to the visual appearance of their respective platforms. But this has changed. Website owners want form styles that fit in with their overall site design more than ever, and the web platform has changed to make this more possible.

For some form widgets, it is still difficult to rebuild controls to make them stylable, but we can now use CSS to style many form features, though we do need to take extra care to ensure we don't break usability.

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 into three categories:

The good

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

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

The bad

Some elements are more difficult to style, requiring more complex CSS or some more specific tricks:

We describe how to handle these more specific features in the article Advanced form styling .

The ugly

Some elements can't be styled thoroughly using CSS. These include:

Again, we'll describe what can be done in terms of styling these elements in Advanced form styling .

The real problem with all these controls is that they have a very complex structure, and beyond some basic styling (such as changing the width or margin of the control) you generally don't have the ability to style the controls' internal components (such as the date picker calendar, or the button on the <select> that causes the options list to display) making up those widgets.

If you want to thoroughly customize those widgets, you really have to create your own using HTML, CSS, and JavaScript. This is beyond the scope of the core form articles, but we do look at this in an advanced article How to build custom form controls .

注意: there are some proprietary CSS pseudo-elements available that allow you to style internal components of these form controls, such as ::-moz-range-track , but these are not consistent across browsers, so can't be relied upon. We will mention these later as well.

The good

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. We already looked at some simple form styling in Your first form ,和 CSS 构建块 module contains some useful form styling essentials 也。

As well as the basic CSS tools covered above, we've also been provided with several selectors — UI pseudo-classes — that enable styling based on the current state of the UI. We cover these in detail in the next article, UI pseudo-classes .

We'll walk through an example at the end of this article to give you some more ideas on basic form control styling and placement. Before we do that however, we'd like to say a few words about specific aspects of form styling that are worth knowing about.

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, browser behavior is 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%;
}

					

继承 property value causes the property value to match the computed value of the property of its parent element; inheriting the value of the parent.

The screenshots below show the difference. On the left is the default rendering of an <input type="text"> , <input type="date"> , <select> , <textarea> , <input type="submit"> ,和 <button> in Chrome on macOS, with the platform's default font style in use. On the right are the same elements, with our above style rule 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.

The defaults differed in a number of ways. Inheriting should change their fonts to that of the parent's font family — in this case the default serif font of the parent container. They all do, with a strange exception — <input type="submit"> does not inherit from the parent paragraph in Chrome. Rather, it uses the font-family: system-ui . This is another reason to use <button> elements over their equivalent input types!

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.

Box sizing

All text fields have complete support for every property related to the CSS box model, such as width , height , padding , margin ,和 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. To give the same size to several different widgets, you can use the box-sizing property along with some consistent values for other properties:

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

					

In the screenshot below, the left column shows the default rendering of an <input type="radio">, <input type="checkbox">, <input type="range">, <input type="text">, <input type="date"> input, <select> , <textarea> ,<input type="submit">, and <button> . The right column on the other hand shows the same elements with our above rule applied to them. 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.

box model properties effect most input types.

What may not be apparent via the screenshot 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.

Legend placement

<legend> element is okay to style, but it can be a bit tricky to control placement of it. By default it is always positioned over the top border of its <fieldset> parent, near the top left corner. To position it somewhere else, for example inside the fieldset somewhere, or near the bottom left corner, you need to rely on positioning.

Take the following example:

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;
}

					

<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> )。

<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.

注意: 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.

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 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 "Secret Typewriter" font from fontsquirrel.com — download the TTF file into the same directory as above.
  3. A hand drawn 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 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, in 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.

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.

Overall layout

First, we prepare by defining our @font-face rules, and all the basic styles set on the <body> and <form> elements. If the fontsquirrel output was different to what we described above, you can find the correct @font-face blocks inside your downloaded webfont kit, in the stylesheet.css file (you'll need to replace the below @font-face blocks with them, and update the paths to the font files):

@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  : 1.3rem sans-serif;
  padding : 0.5em;
  margin  : 0;
  background : #222;
}
form {
  position : relative;
  width  : 740px;
  height : 498px;
  margin : 0 auto;
  padding: 1em;
  box-sizing: border-box;
  background : #FFF url(background.jpg);
  /* we create our grid */
  display  : grid;
  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 <label> s are given the right font:

label {
  font : .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 grey, transparent, background (it is always important to have focus style, for usability and keyboard accessibility):

input:focus, textarea:focus {
  background   : rgba(0,0,0,.1);
  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 textareas

<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 every one 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

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

button {
  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;
}

					

The final result

And voila! Your form should now look like this:

注意: 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 ).

Test your skills!

You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Styling basics .

摘要

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.

In this module

高级话题

发现此页面有问题吗?

最后修改: , 由 MDN 贡献者

  1. Complete beginners start here!
  2. Web 快速入门
    1. Getting started with the Web overview
    2. 安装基本软件
    3. What will your website look like?
    4. 处理文件
    5. HTML 基础
    6. CSS 基础
    7. JavaScript 基础
    8. 发布您的网站
    9. How the Web works
  3. HTML — Structuring the Web
  4. HTML 介绍
    1. Introduction to HTML overview
    2. Getting started with HTML
    3. What's in the head? Metadata in HTML
    4. HTML text fundamentals
    5. Creating hyperlinks
    6. Advanced text formatting
    7. Document and website structure
    8. Debugging HTML
    9. Assessment: Marking up a letter
    10. Assessment: Structuring a page of content
  5. 多媒体和嵌入
    1. Multimedia and embedding overview
    2. Images in HTML
    3. Video and audio content
    4. From object to iframe — other embedding technologies
    5. Adding vector graphics to the Web
    6. Responsive images
    7. Assessment: Mozilla splash page
  6. HTML 表格
    1. HTML tables overview
    2. HTML table basics
    3. HTML Table advanced features and accessibility
    4. Assessment: Structuring planet data
  7. CSS — Styling the Web
  8. CSS 第一步
    1. CSS first steps overview
    2. What is CSS?
    3. Getting started with CSS
    4. How CSS is structured
    5. How CSS works
    6. Using your new knowledge
  9. CSS 构建块
    1. CSS building blocks overview
    2. Cascade and inheritance
    3. CSS 选择器
    4. The box model
    5. Backgrounds and borders
    6. Handling different text directions
    7. Overflowing content
    8. Values and units
    9. Sizing items in CSS
    10. Images, media, and form elements
    11. Styling tables
    12. Debugging CSS
    13. Organizing your CSS
  10. 样式化文本
    1. Styling text overview
    2. Fundamental text and font styling
    3. Styling lists
    4. Styling links
    5. Web fonts
    6. Assessment: Typesetting a community school homepage
  11. CSS 布局
    1. CSS layout overview
    2. Introduction to CSS layout
    3. Normal Flow
    4. Flexbox
    5. Grids
    6. Floats
    7. 位置
    8. Multiple-column Layout
    9. Responsive design
    10. Beginner's guide to media queries
    11. Legacy Layout Methods
    12. Supporting Older Browsers
    13. Fundamental Layout Comprehension
  12. JavaScript — Dynamic client-side scripting
  13. JavaScript 第一步
    1. JavaScript first steps overview
    2. What is JavaScript?
    3. A first splash into JavaScript
    4. What went wrong? Troubleshooting JavaScript
    5. Storing the information you need — Variables
    6. Basic math in JavaScript — Numbers and operators
    7. Handling text — Strings in JavaScript
    8. Useful string methods
    9. 数组
    10. Assessment: Silly story generator
  14. JavaScript 构建块
    1. JavaScript building blocks overview
    2. Making decisions in your code — Conditionals
    3. Looping code
    4. Functions — Reusable blocks of code
    5. Build your own function
    6. Function return values
    7. 事件介绍
    8. Assessment: Image gallery
  15. 引入 JavaScript 对象
    1. Introducing JavaScript objects overview
    2. Object basics
    3. 对象原型
    4. Object-oriented programming concepts
    5. Classes in JavaScript
    6. Working with JSON data
    7. Object building practice
    8. Assessment: Adding features to our bouncing balls demo
  16. 异步 JavaScript
    1. Asynchronous JavaScript overview
    2. General asynchronous programming concepts
    3. Introducing asynchronous JavaScript
    4. Cooperative asynchronous Java​Script: Timeouts and intervals
    5. Graceful asynchronous programming with Promises
    6. Making asynchronous programming easier with async and await
    7. Choosing the right approach
  17. 客户端侧 Web API
    1. 客户端侧 Web API
    2. Introduction to web APIs
    3. Manipulating documents
    4. Fetching data from the server
    5. Third party APIs
    6. Drawing graphics
    7. Video and audio APIs
    8. Client-side storage
  18. Web forms — Working with user data
  19. Core forms learning pathway
    1. Web forms overview
    2. Your first form
    3. How to structure a web form
    4. Basic native form controls
    5. The HTML5 input types
    6. Other form controls
    7. Styling web forms
    8. Advanced form styling
    9. UI pseudo-classes
    10. Client-side form validation
    11. Sending form data
  20. Advanced forms articles
    1. How to build custom form controls
    2. Sending forms through JavaScript
    3. CSS property compatibility table for form controls
  21. Accessibility — Make the web usable by everyone
  22. Accessibility guides
    1. Accessibility overview
    2. What is accessibility?
    3. HTML: A good basis for accessibility
    4. CSS and JavaScript accessibility best practices
    5. WAI-ARIA basics
    6. Accessible multimedia
    7. Mobile accessibility
  23. Accessibility assessment
    1. Assessment: Accessibility troubleshooting
  24. Tools and testing
  25. Client-side web development tools
    1. Client-side web development tools index
    2. Client-side tooling overview
    3. Command line crash course
    4. Package management basics
    5. Introducing a complete toolchain
    6. Deploying our app
  26. Introduction to client-side frameworks
    1. Client-side frameworks overview
    2. Framework main features
  27. React
    1. Getting started with React
    2. Beginning our React todo list
    3. Componentizing our React app
    4. React interactivity: Events and state
    5. React interactivity: Editing, filtering, conditional rendering
    6. Accessibility in React
    7. React resources
  28. Ember
    1. Getting started with Ember
    2. Ember app structure and componentization
    3. Ember interactivity: Events, classes and state
    4. Ember Interactivity: Footer functionality, conditional rendering
    5. Routing in Ember
    6. Ember resources and troubleshooting
  29. Vue
    1. Getting started with Vue
    2. Creating our first Vue component
    3. Rendering a list of Vue components
    4. Adding a new todo form: Vue events, methods, and models
    5. Styling Vue components with CSS
    6. Using Vue computed properties
    7. Vue conditional rendering: editing existing todos
    8. Focus management with Vue refs
    9. Vue resources
  30. Svelte
    1. Getting started with Svelte
    2. Starting our Svelte Todo list app
    3. Dynamic behavior in Svelte: working with variables and props
    4. Componentizing our Svelte app
    5. Advanced Svelte: Reactivity, lifecycle, accessibility
    6. Working with Svelte stores
    7. TypeScript support in Svelte
    8. Deployment and next steps
  31. Angular
    1. Getting started with Angular
    2. Beginning our Angular todo list app
    3. Styling our Angular app
    4. Creating an item component
    5. Filtering our to-do items
    6. Building Angular applications and further resources
  32. Git and GitHub
    1. Git and GitHub overview
    2. Hello World
    3. Git Handbook
    4. Forking Projects
    5. About pull requests
    6. Mastering Issues
  33. Cross browser testing
    1. Cross browser testing overview
    2. Introduction to cross browser testing
    3. Strategies for carrying out testing
    4. Handling common HTML and CSS problems
    5. Handling common JavaScript problems
    6. Handling common accessibility problems
    7. Implementing feature detection
    8. Introduction to automated testing
    9. Setting up your own test automation environment
  34. Server-side website programming
  35. 第一步
    1. First steps overview
    2. Introduction to the server-side
    3. Client-Server overview
    4. Server-side web frameworks
    5. Website security
  36. Django Web 框架 (Python)
    1. Django web framework (Python) overview
    2. 介绍
    3. 设置开发环境
    4. Tutorial: The Local Library website
    5. Tutorial Part 2: Creating a skeleton website
    6. Tutorial Part 3: Using models
    7. Tutorial Part 4: Django admin site
    8. Tutorial Part 5: Creating our home page
    9. Tutorial Part 6: Generic list and detail views
    10. Tutorial Part 7: Sessions framework
    11. Tutorial Part 8: User authentication and permissions
    12. Tutorial Part 9: Working with forms
    13. Tutorial Part 10: Testing a Django web application
    14. Tutorial Part 11: Deploying Django to production
    15. Web application security
    16. Assessment: DIY mini blog
  37. Express Web Framework (node.js/JavaScript)
    1. Express Web Framework (Node.js/JavaScript) overview
    2. Express/Node introduction
    3. Setting up a Node (Express) development environment
    4. Express tutorial: The Local Library website
    5. Express Tutorial Part 2: Creating a skeleton website
    6. Express Tutorial Part 3: Using a database (with Mongoose)
    7. Express Tutorial Part 4: Routes and controllers
    8. Express Tutorial Part 5: Displaying library data
    9. Express Tutorial Part 6: Working with forms
    10. Express Tutorial Part 7: Deploying to production
  38. Further resources
  39. Common questions
    1. HTML questions
    2. CSS questions
    3. JavaScript questions
    4. Web mechanics
    5. Tools and setup
    6. Design and accessibility