linkedlist:

Disabling an entire <form> in HTML

#37 · · HTML, CSS

Form controls usually have an optional disabled attribute to make interacting with them impossible. You cannot change disabled input fields or use disabled buttons. But the form element itself does not have such a disabled attribute. It is therefore not possible to disable a complete HTML form including all its descendants directly.

Luckily, there is a simple work-around: the fieldset element. If this element has the disabled attribute, all descendant form controls are disabled as well. Usually, the fieldset element is used to group several controls within a form. But it is also perfectly valid to only have a single fieldset in a form. Optionally, you can even add a legend element to describe your form group.

An example usage of the fieldset element can be seen below. To disable all form controls within a fieldset, use the disabled attribute like this <fieldset disabled>.

<form>
  <fieldset>
    <!-- your form controls -->
    <button>Disabled when fieldset is disabled</button>
  </fieldset>
</form>

You probably already have some CSS styling that should apply to disabled form controls. This usually also works within a field set without changing anything. Just make sure to use the proper selectors, i.e. button:disabled instead of button[disabled].

By default, most browsers apply a border and some spacings to fieldset elements. That makes sense if they are actually used to group different form controls together. But for this use case, we likely don't want that default styling. You could remove spacings and the border with the usual CSS padding:0; margin:0; border-width:0. But it is even better to set display: contents which has the effect that the fieldset—but not is descendants—is visually removed. That resolves problematic spacings and properly falls back to collapsing margins.

fieldset {
  display: contents;
}