Search code examples
cssformsalignmentstylinguswds

USWDS - How to align form labels to the left of inputs?


I'm using the U.S. Web Design System (USWDS) in a project I'm working on, and I'm struggling with something that seems superficially like it should be quite simple: How can I align form labels so they appear to the left of their corresponding inputs, instead of above them?

Some other CSS libraries call this a horizontal form but I've also seen it referred to as "inline" fields.

According to this answer it's possible to achieve the result I want using modern CSS Grid layout, but so far I haven't figured out how to make that play nicely with the USWDS styling, which does not use CSS Grid.

Can anyone help me to either:

  • Create a horizontal form using some combination of USWDS components and utility classes, or if that's impractical...
  • Produce a horizontal form by overriding the USWDS styling with custom CSS, but without causing too much conflict or breaking with the standard?

Below is a simplified snippet of my HTML:

<link href="https://cdn.jsdelivr.net/npm/uswds@2.8.0/dist/css/uswds.min.css" rel="stylesheet" />


<form class="usa-form">
    <div class="usa-form-group">
        <label class="usa-label" for="somefield1">Sample label</label>
        <input class="usa-input" type="number" name="somefield1" value=0 />
    </div>
    <div class="usa-form-group">
        <label class="usa-label" for="somefield2">Another label</label>
        <input class="usa-input" type="number" name="somefield2" value=0 />
    </div>
</form>


Solution

  • You can use flex on the usa-form-group to get them positioned next to each other as shown in this Code Sandbox, with some other minor touchups to the element margins https://codesandbox.io/s/nostalgic-moon-q7i7f?file=/styles.css