Home > front end >  CSS center positioning
CSS center positioning

Time:11-23

I have kind of difficult css positioning for me and need help. The problem is a have a row of div with flex-wrap: wrap. (picture 1)

picture 1

Each div have 50% width so we have 2 columns. I need each input of 2 element in row have to be on the the same position. (picture 2)

picture 2

You can see that all element on the same label, independent of title's height and error's height. I tried to use align-items: flex-start/end, but it doesn't work cause if you use start you depend on title's height and if you use flex-end then you depend on error's height. In both way moved on the different level. I hope that I explained clear. Can you tell me how I can achieve this behavior?

I tried to use different flex-items properties value, but it didn't work. I would appreciate if you tell me how to place divs like on the picture 2.

CodePudding user response:

I created a pen to demonstrate how this can be done with CSS Grid, but for those that want to see the code, here it is:


<form >
  <div >
    <label for="1">Input label</label>
    <input id="1" type="text">
  </div>
  <div >
    <label for="2">Input label</label>
    <input id="2" type="text">
    <div>Some error, maybe long</div>
  </div>
    <div >
    <label for="3">Input label</label>
    <input id="3" type="text">
  </div>
  <div >
    <label for="4">Input label</label>
    <input id="4" type="text">
    <div>A really, lreally looooooong error message that wraps onto multiple lines and may never happen in real life</div>
  </div>
    </div>
    <div >
    <label for="5">Input label that is running onto multiple lines and is the root of the issue</label>
    <input id="5" type="text">
          <div>A really, lreally looooooong error message that wraps onto multiple lines and may never happen in real life</div>
  </div>
  <div >
    <label for="6">Input label</label>
    <input id="6" type="text">
  </div>
</form>
.form {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 1rem;
}
.form-group {
  display: grid;
  grid-template-rows: 1fr auto 1fr;
}
label {
  font-weight: bold;
  align-self: end;
}

The use of grid-template-rows, and not aligning elements using the grid container is the secret here.

  • Related