How to align labels in form next to input with CSS?

Spread the love

Sometimes, we want to align labels in form next to input with CSS.

In this article, we’ll look at how to align labels in form next to input with CSS.

How to align labels in form next to input with CSS?

To align labels in form next to input with CSS, we use flexbox.

For instance, we write

<form>
  <div class="wrapper">
    <div class="input-group">
      <label for="user_name">name:</label>
      <input type="text" id="user_name" />
    </div>
    <div class="input-group">
      <label for="user_pass">Password:</label>
      <input type="password" id="user_pass" />
    </div>
  </div>
</form>

to add a form.

Then we write

body {
  color: white;
  font-family: arial;
  font-size: 1.2em;
}
form {
  margin: 0 auto;
  padding: 20px;
  background: #444;
}
.input-group {
  margin-top: 10px;
  width: 60%;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}
label,
input {
  flex-basis: 100px;
}

to make the elements with class input-group a flex container with display: flex;.

We make its contents spread horizontally with justify-content: space-between;.

And we add flex-wrap: wrap; to make the contents wrap when the width is too narrow to fit everything in 1 row.

Conclusion

To align labels in form next to input with CSS, we use flexbox.

Leave a Reply

Your email address will not be published.