Kevin Powell - CommunityKP-C
Kevin Powell - Community•3y ago•
9 replies
Arto

How to vertically align label next to input form in flexbox CSS

Hey guys, really sorry for wasting someone's time on this probably stupid question, but I couldn't find a solid answer after 2 days of research by myself:

I am trying to build up a simple form using flexbox. But the problem is that label (specifically in flexbox) isn't pixel perfect centered next to input form (which is usually not a problem with inline block elements.) I am basically trying to line up placeholder text to label text so they would be on the same line, while in my example (see the img i attached) placeholder is slightly higher than the label.
I found few tricks setting up line-height and vertical-align: text-top, but as far as I understood they only work when you use inline-block elements.
AFAIK using align-items:center in the flexbox parent should fix aligning problems on the main axis, but it didn't help.

The only solution I know is to just manually add margin-bottom the label element, which obviously works, but I heard that applying extra margins might bad practice.

<form>
  <fieldset>
    <div class="field">
      <label>Name:</label>
      <input type="text" placeholder="Name" />
    </div>
    <button type="submit"> Submit </button>
  </fieldset>
</form>


.field {
  width: 100%;
  display: flex;
  margin-bottom: 10px;
  align-items: center;
}

input {
  margin-left: 5px;
}
exmpl.png
Was this page helpful?