Cover image for Breaking the law with <fieldset>

Breaking the law with <fieldset>

jfbrennan profile image Jordan Brennan ・2 min read

In the past few years I've moved to a "classes for styles only" design philosophy. I believe all other use cases - custom UI components, test hooks & third-party integrations, and event binding - have better solutions than a boilerplate div with classes, and forms are no exception.

The challenge though is form fields, like input and select, require a wrapping element in order to implement layouts and custom styles and there is no native element for that. So classes are used:

<div class="form-group">
  <input class="form-control">
Enter fullscreen mode Exit fullscreen mode

But wanting to invent less and leverage more got me looking at fieldset with criminal intentions and, although uncommon, using it with just one input does work. And is technically valid markup. And MDN even has an example.

The result is the most clean and uniform form code I've ever seen:

    <input type="tel">
    <input placeholder="Street">
    <input placeholder="City">
      <option value="AL">Alabama</option>
      <option value="WY">Wyoming</option>
Enter fullscreen mode Exit fullscreen mode

This enables the necessary selectors to customize form fields:

fieldset input,
fieldset select,
fieldset textarea {
  border: 1px solid var(--m-color-gray-1);

fieldset textarea { 
  resize: vertical;

Enter fullscreen mode Exit fullscreen mode

Does this push the boundaries a bit? Maybe, but I've done the same with bulletless lists and a custom "remove" button type in M- and it's all been a great experience so far. It's the HTML I wish we had without over-engineering to get it!

Go take a look at M- forms and try the live code demos to get a feel for it. Breaking the law feels good!


Editor guide