Apparence des formulaires HTML

  • Raccourci de la révision : HTML/Formulaires/Apparence_des_formulaires_HTML
  • Titre de la révision : Apparence des formulaires HTML
  • ID de la révision : 387563
  • Créé :
  • Créateur : FredB
  • Version actuelle ? Non
  • Commentaire

Contenu de la révision

Dans cet article, nous allons apprendre comment utiliser CSS avec les formulaires HTML pour (espérons) améliorer leur apparence. Étonnament, ceci peut être délicat. Pour des raisons techniques et historiques, les blocs de formulaires ne s'allient pas très bien avec CSS. À cause de ces difficultés, de nombreux développeurs préfèrent construire leurs propres blocs HTML pour avoir plus de maîtrise sur leur apparence. Toutefois, avec les navigateurs modernes, les web designers ont de plus en plus d'emprise sur l'apparence de leurs formulaires. Voyons cela de plus près.

Pourquoi est-ce si dur de modifier l'apparence des formulaires avec CSS ?

Dans la jeunesse du Web — aux alentours de 1995 — les formulaires ont été ajoutés à HTML dans la spécification HTML 2. À cause de la complexité des formulaires, les implémenteurs ont préféré s'appuyer sur le système d'exploitation pour les gérer et les afficher.

Quelques années plus tard, CSS a été créé et ce qui était une nécessité technique — c'est-à-dire, utiliser les blocs natufs pour les formulaires — est devenu un préalable stylistique. Et dans la jeunesse de CSS, l'apparence des formulaires n'était pas une priorité.

Puisque les utilisateurs se sont habitués à l'apparence de leur plateformes respectives, les fournisseurs de navigateurs étaient rétissants à rendre possible la modification de l'apparence des formulaires. Et pour être honnête, il est toujours extrêmement difficile de reconstruire tous les contrôles pour que leur apparence soit modifiable.

Même aujourd'hui, aucun des navigateurs n'a implémenté entièrement CSS 2.1. Le temps faisant, les fournisseurs de navigateurs ont toutefois amélioré la compatibilité de CSS avec les éléments de formulaires, et bien que ce soit de mauvaise réputation pour l'utilisabilité, vous pouvez désormais modifier l'apparene des formulaires HTML.

Tous les blocs ne sont pas créés égaux devant CSS

À présent, quelques difficultés subsistent dans l'utilisation de CSS avec les formulaires. Ces problèmes peuvent être classés dans trois catégories.

Le bon

L'apparence de certains éléments peut être modifiée avec peu de problèmes au travers des différentes plateformes. Ceci inclut les éléments structurels suivants :

  1. {{HTMLElement("form")}}
  2. {{HTMLElement("fieldset")}}
  3. {{HTMLElement("label")}}
  4. {{HTMLElement("output")}}

Ceci inclut aussi tous les blocs de champs textuels (qu'ils soient mono ou multilignes) et les boutons.

La brute

L'apparence de certains éléments ne peut être modifiée que rarement et peut nécessiter quelques astuces complexes, et parfois une connaissance avancée de CSS3.

Ceci inclut l'élément {{HTMLElement("legend")}}. Ce dernier ne peux pas être positionné correctement sur toutes les plateformes. De plus, l'apparence des cases à cocher et des boutons radio ne peut pas être modifiée directement. Toutefois, grâce à CSS3 c'est possible de contourner cette limitation. L'apparence du contenu {{htmlattrxref("placeholder", "input")}} ne peut pas être modifiée d'une manière standard. Mais tous les navigateurs qui sont compatible avec cet attribut ont aussi implémenté des pseudo-classes ou pseudo-élément propriétaires qui permettent de modifier son apparence.

Nous allons voir comment gérer ces cas dans l'article apparence avancée des formulaires HTML.

Le truand

L'apparence de certains éléments n'est tout bonnement pas modifiable en utilisant CSS. Ceci inclut toutes les interfaces avancées comme les intervalles, la sélection de couleur ou de date ainsi que les éléments déroulants, incluant les éléments {{HTMLElement("select")}}, {{HTMLElement("option")}}, {{HTMLElement("optgroup")}} et {{HTMLElement("datalist")}}. La sélection de fichiers est aussi connue pour ne pas pouvoir changer d'apparence. Les nouveaux élément {{HTMLElement("progress")}} et {{HTMLElement("meter")}} font aussi partie de cette catégorie.

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. We'll learn how to do this in the article How to build custom form widgets.

Basic styling

To style elements that are easy to style with CSS, you shouldn't face 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 more painlessly.

Search fields

Search boxes are the only kind of text fields that can be a little tricky to style. On WebKit based browsers (Chrome, Safari, etc.) you'll have to tweak it with the -webkit-appearance proprietary property. We will discuss this property further in the article: Advanced styling for HTML forms.

Example

<form>
  <input type="search">
</form>
input[type=search] {
  border: 1px dotted #999;
  border-radius: 0;

  -webkit-appearance: none;
}

This is a screenshot of a search filed on Chrome, with and without the use of -webkit-appearance

As you can see on this screenshot of the search field on Chrome, the two fields have a border set as in our example, but the first field is rendered without using the -webkit-appearance property where the second is rendered using -webkit-appearance:none. The difference is noticeable.

Fonts and text

CSS font and text features can be used easily with any widget (and yes, you can use {{cssxref("@font-face")}} with form widgets). However, browsers' behaviors are often inconsistent. By default, some widgets do not inherit {{cssxref("font-family")}} and {{cssxref("font-size")}} from their parents. And 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 Firefox 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.

This is a screenshot of the main form widgets on Firefox on Mac OSX, with and without font harmonization

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 model

All text fields have complete support for every property related to the CSS box model ({{cssxref("width")}}, {{cssxref("height")}}, {{cssxref("padding")}}, {{cssxref("margin")}}, and {{cssxref("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 {{cssxref("box-sizing")}} property:

input, textarea, select, button {
  width : 150px;
  margin: 0;

  -webkit-box-sizing: border-box; /* For legacy WebKit based browsers */
     -moz-box-sizing: border-box; /* For all Gecko based browsers */
          box-sizing: border-box;
}

This is a screenshot of the main form widgets on Chrome on Windows 7, with and without the use of box-sizing.

In the screenshot above, the left column is built without {{cssxref("box-sizing")}}, while the right column uses this property with the value border-box. 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.

Positioning

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

legend

The {{HTMLElement("legend")}} element is okay to style except for positioning. In every browser, the {{HTMLElement("legend")}} element is positioned on top of the top border of its {{HTMLElement("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 {{cssxref("position")}} property, but otherwise it is part of the fieldset border.

Because the {{HTMLElement("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, like this:

HTML
<fieldset>
  <legend>Hi!</legend>
  <h1>Hello</h1>
</fieldset>
CSS
legend {
  width: 1px;
  height: 1px;
  overflow: hidden;
}

textarea

By default, all browsers consider the {{HTMLElement("textarea")}} element to be an inline block aligned to the text bottom line. This is rarely what we actually want. To change from inline-block to block, it's pretty easy to use the {{cssxref("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

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>

CSS

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

  1. The postcard background
  2. A typewriter font: The "Secret Typewriter" from fontsquirrel.com
  3. A handdrawn font: The "Journal" from fontsquirrel.com

Now we can dig into the code. First, we prepare the ground by defining our {{cssxref("@font-face")}} rules and all the basics on the {{HTMLElement("body")}} element and the {{HTMLElement("form")}} element.

@font-face{
  font-family : "handwriting";

  src : url('journal.eot');
  src : url('journal.eot?') format('eot'),
        url('journal.woff') format('woff'),
        url('journal.ttf') format('truetype');
}

@font-face{
  font-family : "typewriter";

  src : url('veteran_typewriter.eot');
  src : url('veteran_typewriter.eot?') format('eot'),
        url('veteran_typewriter.woff') format('woff'),
        url('veteran_typewriter.ttf') format('truetype');
}

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 {{HTMLElement("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 {{cssxref("border","borders")}} and {{cssxref("background","backgrounds")}} and redefine their {{cssxref("padding")}} and {{cssxref("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 {{cssxref("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 done, we need to adjust the display of the single and multiple line text fields to match, since they typically don't look the same at all by default.

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 */
}

{{HTMLElement("textarea")}} elements default to being rendered as a block element. The two important things here are the {{cssxref("resize")}} and {{cssxref("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 {{cssxref("overflow")}} property is used to make the field render more consistently across browsers; some browsers default to the value auto and 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 {{HTMLElement("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;

-webkit-transform: rotate(-1.5deg);
   -moz-transform: rotate(-1.5deg);
    -ms-transform: rotate(-1.5deg);
     -o-transform: rotate(-1.5deg);
        transform: rotate(-1.5deg);
}

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

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

And voila! Feel free to try it yourself; as you'll see, it works!

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 from widgets that fall in the "bad" and "ugly" categories.

Source de la révision

<p>Dans cet article, nous allons apprendre comment utiliser <a href="/fr/docs/CSS" title="/fr/docs/CSS">CSS</a> avec les formulaires <a href="/fr/docs/HTML" title="/fr/docs/HTML">HTML</a> pour (espérons) améliorer leur apparence. Étonnament, ceci peut être délicat. Pour des raisons techniques et historiques, les blocs de formulaires ne s'allient pas très bien avec CSS. À cause de ces difficultés, de nombreux développeurs préfèrent <a href="/fr/docs/HTML/Formulaires/Comment_créer_des_blocs_de_formulaires_personnalisés" title="/fr/docs/HTML/Formulaires/Comment_créer_des_blocs_de_formulaires_personnalisés">construire leurs propres blocs HTML</a> pour avoir plus de maîtrise sur leur apparence. Toutefois, avec les navigateurs modernes, les web designers ont de plus en plus d'emprise sur l'apparence de leurs formulaires. Voyons cela de plus près.</p>
<h2 id="Why_is_it_so_hard_to_style_form_widgets_with_CSS.3F">Pourquoi est-ce si dur de modifier l'apparence des formulaires avec CSS&nbsp;?</h2>
<p>Dans la jeunesse du Web —&nbsp;aux alentours de 1995&nbsp;— les formulaires ont été ajoutés à HTML dans la <a href="http://www.ietf.org/rfc/rfc1866.txt" rel="extrenal" title="http://www.ietf.org/rfc/rfc1866.txt">spécification HTML 2</a>. À cause de la complexité des formulaires, les implémenteurs ont préféré s'appuyer sur le système d'exploitation pour les gérer et les afficher.</p>
<p>Quelques années plus tard, CSS a été créé et ce qui était une nécessité technique —&nbsp;c'est-à-dire, utiliser les blocs natufs pour les formulaires&nbsp;— est devenu un préalable stylistique. Et dans la jeunesse de CSS, l'apparence des formulaires n'était pas une priorité.</p>
<p>Puisque les utilisateurs se sont habitués à l'apparence de leur plateformes respectives, les fournisseurs de navigateurs étaient rétissants à rendre possible la modification de l'apparence des formulaires. Et pour être honnête, il est toujours extrêmement difficile de reconstruire tous les contrôles pour que leur apparence soit modifiable.</p>
<p>Même aujourd'hui, aucun des navigateurs n'a implémenté entièrement CSS 2.1. Le temps faisant, les fournisseurs de navigateurs ont toutefois amélioré la compatibilité de CSS avec les éléments de formulaires, et bien que ce soit de mauvaise réputation pour l'utilisabilité, vous pouvez désormais modifier l'apparene des <a href="/fr/docs/HTML/Formulaires" title="/fr/docs/HTML/Formulaires">formulaires HTML</a>.</p>
<h3 id="Not_all_widgets_are_created_equal_when_CSS_is_involved">Tous les blocs ne sont pas créés égaux devant CSS</h3>
<p>À présent, quelques difficultés subsistent dans l'utilisation de CSS avec les formulaires. Ces problèmes peuvent être classés dans trois catégories.</p>
<h4 id="The_good">Le bon</h4>
<p>L'apparence de certains éléments peut être modifiée avec peu de problèmes au travers des différentes plateformes. Ceci inclut les éléments structurels suivants&nbsp;:</p>
<ol>
  <li>{{HTMLElement("form")}}</li>
  <li>{{HTMLElement("fieldset")}}</li>
  <li>{{HTMLElement("label")}}</li>
  <li>{{HTMLElement("output")}}</li>
</ol>
<p>Ceci inclut aussi tous les blocs de champs textuels (qu'ils soient mono ou multilignes) et les boutons.</p>
<h4 id="The_bad">La brute</h4>
<p>L'apparence de certains éléments ne peut être modifiée que rarement et peut nécessiter quelques astuces complexes, et parfois une connaissance avancée de CSS3.</p>
<p>Ceci inclut l'élément {{HTMLElement("legend")}}. Ce dernier ne peux pas être positionné correctement sur toutes les plateformes. De plus, l'apparence des cases à cocher et des boutons radio ne peut pas être modifiée directement. Toutefois, grâce à CSS3 c'est possible de contourner cette limitation. L'apparence du contenu {{htmlattrxref("placeholder", "input")}} ne peut pas être modifiée d'une manière standard. Mais tous les navigateurs qui sont compatible avec cet attribut ont aussi implémenté des pseudo-classes ou pseudo-élément propriétaires qui permettent de modifier son apparence.</p>
<p>Nous allons voir comment gérer ces cas dans l'article <a href="/fr/docs/HTML/Formulaires/Apparence_avancée_des_formulaires_HTML" title="/fr/docs/HTML/Formulaires/Apparence_avancée_des_formulaires_HTML">apparence avancée des formulaires HTML</a>.</p>
<h4 id="The_ugly">Le truand</h4>
<p>L'apparence de certains éléments n'est tout bonnement pas modifiable en utilisant CSS. Ceci inclut toutes les interfaces avancées comme les intervalles, la sélection de couleur ou de date ainsi que les éléments déroulants, incluant les éléments {{HTMLElement("select")}}, {{HTMLElement("option")}}, {{HTMLElement("optgroup")}} et {{HTMLElement("datalist")}}. La sélection de fichiers est aussi connue pour ne pas pouvoir changer d'apparence. Les nouveaux élément {{HTMLElement("progress")}} et {{HTMLElement("meter")}} font aussi partie de cette catégorie.</p>
<p>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. We'll learn how to do this in the article <a href="/en-US/docs/HTML/Forms/How_to_build_custom_form_widgets" title="/en-US/docs/HTML/Forms/How_to_build_custom_form_widgets">How to build custom form widgets</a>.</p>
<h2 id="Basic_styling">Basic styling</h2>
<p>To style <a href="/en-US/docs/HTML/Forms/Styling_HTML_forms#The_good" title="/en-US/docs/HTML/Forms/Styling_HTML_forms#The_good">elements that are easy to style</a> with CSS, you shouldn't face 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 more painlessly.</p>
<h3 id="Search_fields">Search fields</h3>
<p>Search boxes are the only kind of text fields that can be a little tricky to style. On WebKit based browsers (Chrome, Safari, etc.) you'll have to tweak it with the <code>-webkit-appearance</code> proprietary property. We will discuss this property further in the article: <a href="/en-US/docs/Advanced_styling_for_HTML_forms" title="/en-US/docs/Advanced_styling_for_HTML_forms">Advanced styling for HTML forms</a>.</p>
<h4 id="Example">Example</h4>
<pre class="brush: html">
&lt;form&gt;
  &lt;input type="search"&gt;
&lt;/form&gt;
</pre>
<pre class="brush: css">
input[type=search] {
  border: 1px dotted #999;
  border-radius: 0;

  -webkit-appearance: none;
}</pre>
<p><img alt="This is a screenshot of a search filed on Chrome, with and without the use of -webkit-appearance" src="/files/4153/search-chrome-macos.png" style="width: 179px; height: 107px; border-width: 1px; border-style: solid;" /></p>
<p>As you can see on this screenshot of the search field on Chrome, the two fields have a border set as in our example, but the first field is rendered without using the <code>-webkit-appearance</code> property where the second is rendered using <code>-webkit-appearance:none</code>. The difference is noticeable.</p>
<h3 id="Fonts_and_text">Fonts and text</h3>
<p>CSS font and text features can be used easily with any widget (and yes, you can use {{cssxref("@font-face")}} with form widgets). However, browsers' behaviors are often inconsistent. By default, some widgets do not inherit {{cssxref("font-family")}} and {{cssxref("font-size")}} from their parents. And 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:</p>
<pre class="brush: css">
button, input, select, textarea {
  font-family : inherit;
  font-size   : 100%;
}</pre>
<p>The screenshot below shows the difference; on the left is the default rendering of the element in Firefox 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.</p>
<p><img alt="This is a screenshot of the main form widgets on Firefox on Mac OSX, with and without font harmonization" src="/files/4157/font-firefox-macos.png" style="width: 420px; height: 234px; border-width: 1px; border-style: solid;" /></p>
<p>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.</p>
<h3 id="Box_model">Box model</h3>
<p>All text fields have complete support for every property related to the CSS box model ({{cssxref("width")}}, {{cssxref("height")}}, {{cssxref("padding")}}, {{cssxref("margin")}}, and {{cssxref("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.</p>
<p><strong>This is because each widget has their own rules for border, padding and margin.</strong> So if you want to give the same size to several different widgets, you have to use the {{cssxref("box-sizing")}} property:</p>
<pre class="brush: css">
input, textarea, select, button {
  width : 150px;
  margin: 0;

  -webkit-box-sizing: border-box; /* For legacy WebKit based browsers */
     -moz-box-sizing: border-box; /* For all Gecko based browsers */
          box-sizing: border-box;
}</pre>
<p><img alt="This is a screenshot of the main form widgets on Chrome on Windows 7, with and without the use of box-sizing." src="/files/4161/size-chrome-win7.png" style="width: 358px; height: 213px; border-width: 1px; border-style: solid;" /></p>
<p>In the screenshot above, the left column is built without {{cssxref("box-sizing")}}, while the right column uses this property with the value <code>border-box</code>. 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.</p>
<h3 id="Positioning">Positioning</h3>
<p>Positioning of HTML form widgets is generally not a problem; however, there are two elements you should take special note of:</p>
<h4 id="legend">legend</h4>
<p>The {{HTMLElement("legend")}} element is okay to style except for positioning. In every browser, the {{HTMLElement("legend")}} element is positioned on top of the top border of its {{HTMLElement("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 {{cssxref("position")}} property, but otherwise it is part of the fieldset border.</p>
<p>Because the {{HTMLElement("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, like this:</p>
<h5 id="HTML">HTML</h5>
<pre class="brush: html">
&lt;fieldset&gt;
  &lt;legend&gt;Hi!&lt;/legend&gt;
  &lt;h1&gt;Hello&lt;/h1&gt;
&lt;/fieldset&gt;</pre>
<h5 id="CSS">CSS</h5>
<pre class="brush: css">
legend {
  width: 1px;
  height: 1px;
  overflow: hidden;
}</pre>
<h4 id="textarea">textarea</h4>
<p>By default, all browsers consider the {{HTMLElement("textarea")}} element to be an inline block aligned to the text bottom line. This is rarely what we actually want. To change from <code>inline-block</code> to <code>block</code>, it's pretty easy to use the {{cssxref("display")}} property. But if you want to use it inline, it's common to change the vertical alignment:</p>
<pre class="brush: css">
textarea {
  vertical-align: top;
}</pre>
<h2 id="Example">Example</h2>
<p>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:</p>
<p><img alt="This is what we want to achieve with HTML and CSS" src="/files/4149/screenshot.png" style="width: 370px; height: 249px; border-width: 1px; border-style: solid;" /></p>
<h3 id="HTML">HTML</h3>
<p>The HTML is only slightly more involved than the example we used in <a href="/en-US/docs/HTML/Forms/My_first_HTML_form" title="/en-US/docs/HTML/Forms/My_first_HTML_form">the first article of this guide</a>; it just has a few extra IDs and a title.</p>
<pre class="brush: html">
&lt;form&gt;
  &lt;h1&gt;to: Mozilla&lt;/h1&gt;

  &lt;div id="from"&gt;
    &lt;label for="name"&gt;from:&lt;/label&gt;
    &lt;input type="text" id="name" name="user_name"&gt;
  &lt;/div&gt;

  &lt;div id="reply"&gt;
    &lt;label for="mail"&gt;reply:&lt;/label&gt;
    &lt;input type="email" id="mail" name="user_email"&gt;
  &lt;/div&gt;

  &lt;div id="message"&gt;
    &lt;label for="msg"&gt;Your message:&lt;/label&gt;
    &lt;textarea id="msg" name="user_message"&gt;&lt;/textarea&gt;
  &lt;/div&gt;
 
  &lt;div class="button"&gt;
    &lt;button type="submit"&gt;Send your message&lt;/button&gt;
  &lt;/div&gt;
&lt;/form&gt;</pre>
<h3 id="CSS">CSS</h3>
<p>This is where the fun begins! Before we start coding, we need three additional elements:</p>
<ol>
  <li>The postcard <a href="/files/4151/background.jpg" title="The postcard background">background</a></li>
  <li>A typewriter font: <a href="http://www.fontsquirrel.com/fonts/Secret-Typewriter" rel="external" title="http://www.fontsquirrel.com/fonts/Secret-Typewriter">The "Secret Typewriter" from fontsquirrel.com</a></li>
  <li>A handdrawn font: <a href="http://www.fontsquirrel.com/fonts/Journal" rel="external" title="http://www.fontsquirrel.com/fonts/Journal">The "Journal" from fontsquirrel.com</a></li>
</ol>
<p>Now we can dig into the code. First, we prepare the ground by defining our {{cssxref("@font-face")}} rules and all the basics on the {{HTMLElement("body")}} element and the {{HTMLElement("form")}} element.</p>
<pre class="brush: css">
@font-face{
  font-family : "handwriting";

  src : url('journal.eot');
  src : url('journal.eot?') format('eot'),
        url('journal.woff') format('woff'),
        url('journal.ttf') format('truetype');
}

@font-face{
  font-family : "typewriter";

  src : url('veteran_typewriter.eot');
  src : url('veteran_typewriter.eot?') format('eot'),
        url('veteran_typewriter.woff') format('woff'),
        url('veteran_typewriter.ttf') format('truetype');
}

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);
}</pre>
<p>Now we can position our elements, including the title and all the form elements.</p>
<pre class="brush: css">
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;
}</pre>
<p>That's where we start working on the form elements themselves. First, let's ensure that the {{HTMLElement("label")}}s are given the right font.</p>
<pre class="brush: css">
label {
  font : .8em "typewriter", sans-serif;
}</pre>
<p>The text fields require some common rules. Simply put, we remove their {{cssxref("border","borders")}} and {{cssxref("background","backgrounds")}} and redefine their {{cssxref("padding")}} and {{cssxref("margin")}}.</p>
<pre class="brush: css">
input, textarea {
  font    : .9em/1.5em "handwriting", sans-serif;

  border  : none;
  padding : 0 10px;
  margin  : 0;
  width   : 240px;

  background: none;
}</pre>
<p>When one of these fields gains focus, we highlight them with a light grey, transparent, background. Note that it's important to add the {{cssxref("outline")}} property in order to remove the default focus highlight added by some browsers.</p>
<pre class="brush: css">
input:focus, textarea:focus {
  background   : rgba(0,0,0,.1);
  border-radius: 5px;
  outline      : none;
}</pre>
<p>Now that our text fields are done, we need to adjust the display of the single and multiple line text fields to match, since they typically don't look the same at all by default.</p>
<p>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:</p>
<pre class="brush: css">
input {
    height: 2.5em; /* for IE */
    vertical-align: middle; /* This is optional but it makes legacy IEs look better */
}</pre>
<p>{{HTMLElement("textarea")}} elements default to being rendered as a block element. The two important things here are the {{cssxref("resize")}} and {{cssxref("overflow")}} properties. Because our design is a fixed-size design, we will use the <code>resize</code> property to prevent users from resizing our multi-line text field. The {{cssxref("overflow")}} property is used to make the field render more consistently across browsers; some browsers default to the value <code>auto</code> and some default to the value <code>scroll</code>. In our case, it's better to be sure every one will use <code>auto</code>.</p>
<pre class="brush: css">
textarea {
  display : block;

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

  resize  : none;
  overflow: auto;
}</pre>
<p>The {{HTMLElement("button")}} element is really convenient with CSS; you can do whatever you want, even using <a href="/en-US/docs/CSS/Pseudo-elements" title="/en-US/docs/CSS/Pseudo-elements">pseudo-elements</a>!</p>
<pre class="brush: css">
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;

-webkit-transform: rotate(-1.5deg);
   -moz-transform: rotate(-1.5deg);
    -ms-transform: rotate(-1.5deg);
     -o-transform: rotate(-1.5deg);
        transform: rotate(-1.5deg);
}

button:after {
  content: " &gt;&gt;&gt;";
}

button:hover,
button:focus {
  outline   : none;
  background: #000;
  color   : #FFF;
}</pre>
<p>And voila! Feel free to try it yourself; as you'll see, it works!</p>
<h2 id="Conclusion">Conclusion</h2>
<p>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 <a href="http://necolas.github.com/normalize.css" rel="external" title="http://necolas.github.com/normalize.css">the normalize.css project</a>.</p>
<p><a href="/en-US/docs/Advanced_styling_for_HTML_forms" title="/en-US/docs/Advanced_styling_for_HTML_forms">In the next article</a>, we will see how to handle from widgets that fall in the "bad" and "ugly" categories.</p>
Revenir à cette révision