How to style the form with the label above inputs with CSS?

Spread the love

To style the form with the label above inputs with JavaScript, we use flexbox.

For instance, we write

<form id="survey-form1">
  <label for="name1">Name</label>
  <input type="text" id="name1" />

  <label for="email1">Email</label>
  <input type="email" id="email" />
</form>

<form id="survey-form2">
  <div class="inputPair">
    <label for="name2">Name2</label>
    <input type="text" id="name2" />
  </div>
  <div class="inputPair">
    <label for="email2">Email2</label>
    <input type="email" id="email2" />
  </div>
</form>

to add forms with labels and inputs.

Then we write

#survey-form1 label {
  display: flex;
  flex-direction: column;
}

#survey-form2 {
  display: flex;
  flex-direction: row;
}

.inputPair {
  display: flex;
  flex-direction: column;
  margin-right: 10px;
}

to make the divs with class inputPair flex containers with display: flex;

And we add flex-direction: column; to make the label stay above the input.

Leave a Reply

Your email address will not be published. Required fields are marked *