What is the cleanest way to make a form without using hundreds divs?

Hi, I haven’t touch CSS for months and I forgot what is the best way to make a form with a HTML like this ? I don’t like use many divs. Would you use flexbox or grid ? I’m asking as I will have to “re learn” one of them to be able to make my form in a short time and keep my html clean.

I want to be able to put my input next to my label or my label on the top of my input. Is it possible by using an HTML like this ?

Thanks :slight_smile:

 <div class="container">
      <form>
        <label for='prenom'>Prenom</label>
        <input type='text' id='prenom' name='prenom'>

        <label for='nom'>Nom</label>
        <input type='text' id='nom' name='nom'>

        <p>Vous etes :</p>
        <input type="radio" id="homme" name="sexe" value="homme">
        <label for="homme">Homme</label>

        <input type="radio" id="femme" name="sexe" value="femme">
        <label for="femme">Femme</label>

        <p>Votre animal:</p>
        <input type="checkbox" name="chien" id="chien">
        <label for="chien">Chien</label>

        <input type="checkbox" name="chat" id="chat">
        <label for="chat">Chat</label>
        </form>
      </div>

You start with the basics (the minimum you need to create a form) and then you add divs as needed for styling. There is nothing wrong with using divs like this. Yes, it can get a little out of hand if you aren’t careful (commonly known as ‘divitis’). And CSS does provide you many layout options which will help keep the number of divs down. But when you need a div there is nothing wrong with adding one.

By default, isn’t the label already to the side of the input? It is in my browser. If you want to put it on top of the label then you could just set the display on the label to block (I would only do this for the text inputs, not the radio/check box inputs). These are very simple changes and may not work for what you intend to do but it is possible to change the layout without flexbox/grid. But for anything more complicated you are probably going to have to wrap a div around each label/input pair.

2 Likes