skip to Main Content

I would like to realize this with flexbox:

Desired outcome

Currently, I encapsulate in groups of inputs, where I apply display flex. I’d like if the last element is odd (if I have 3, 5… inputs) that the last one is not filling the whole space and just get the size of the other ones (that are filling the space).

Is there an easy way to achieve this?

In my current code, I did to input groups (the first one with the 3 first, then another one for password):

<div class="inputsGroup">
  <div class="input">
    <label for="firstname">Prénom</label>
    <input type="text" placeholder="Jean" name="firstname">
  </div>
  <div class="input">
    <label for="lastname">Nom</label>
    <input type="text" placeholder="Dupont" name="lastname">
  </div>
  <div class="input">
    <label for="email">Adresse e-mail</label>
    <input type="text" placeholder="[email protected]" name="email">
  </div>
</div>
<div class="inputsGroup">
  <div class="input">
    <label for="password">Mot de passe</label>
    <input type="password" name="password">
    <p class="body-2 info">Votre mot de passe doit contenir au minimum 8 caractères contenant lettres, chiffres et caractères spéciaux.</p>
  </div>
  <div class="input">
    <label for="passwordConfirmation">Confirmation du mot de passe</label>
    <input type="password" name="passwordConfirmation">
  </div>
</div>
<div class="loginButtons">
  <button class="btn btn-primary loginSubmit">Connexion</button>
  <button class="btn btn-tertiary passwordReset">Mot de passe oublié</button>
</div>

2

Answers


  1. Chosen as BEST ANSWER

    As recommended in the comments, using display: grid is more appropriate.

    This is what I've done :

    .inputsGroup{
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            grid-gap: 24px;
            margin-bottom: 24px;

    This creates a grid with 2 columns that are both taking the available space (they balance each other). And then, the third element is moved to a new line.


  2. .inputsGroup {
      display: flex;
      flex-wrap: wrap;
    }
    
    .inputsGroup .input {
      flex: 1 1 33.33%; /* Set the flex property to distribute the inputs equally */
      margin-right: 10px; /* Optional: Add margin between input groups */
    }
    
    .inputsGroup .input:last-child {
      flex: 0 1 auto; /* Set the flex property of the last input to not fill the space */
    }
    
    .loginButtons {
      display: flex;
      justify-content: space-between; /* Optional: Adjust the alignment of login buttons */
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search