Search code examples
htmlmarkupsemantic-markup

What's the best semantic way to wrap a search area?


I'd like to take advantage of the improved semantics of html5. I'm creating a search area, and the search area should have a background and contain search related things, like autocomplete and search hints.

Is there some consensus around what type of element something like a search area should be wrapped in?

  • Should it be a NAV because searching is a method of navigation?
  • Should it be a SECTION because it's a discreet section of the page?
  • Should it be a DIV because the wrapping of search related elements has no clear semantics?

The markup is something like this:

<?whatElement?>
  <input type="search" placeholder="Search for a name or ID..." required />
  <a href="#" class="search button">Search</a>
</?whatElement?>

Thanks for your thoughts.


Solution

  • I am aware this question already has a chosen answer, but it ranked so high in my Google search for "semantic search form" that I feel the need to contribute what I believe to be a slightly better answer, semantically and from a standards standpoint.

    <section role="search">
        <form action="#" method="get">
            <fieldset>
                <legend>Search this website:</legend>
                <label for="s">
                    <input type="search" name="s" id="s" placeholder="Search..." maxlength="200" />
                </label>
                <button type="submit" title="Search this website now">Submit</button>
            </fieldset>
        </form>
    </section>

    Of course, I made a series of assumptions and populated the HTML with some default values (action, get, the id and name of the input, etc) and with no classnames for the elements (which I always tend to use in favor of generic element names or, Heaven forbid, IDs) but you should adapt to your own needs.

    For example, some additions on top of the excellent contributions above: the first child of any form should always be a <fieldset> tag and have a <legend> attached (visible or not - https://www.w3.org/TR/WCAG20-TECHS/H71.html ), and all <input> tags should have a connected <label> tag through the for and id properties (https://www.w3.org/TR/WCAG20-TECHS/H44.html - I find it easier to just wrap the input in the label so as not to forget connecting them). All call to action elements should have a title (for SEO and usability, to reinforce the action the user is about to make just before she makes it), etc.