skip to Main Content

I am trying to center a checkbox input to its text input siblings. The text inputs have label on top of them and the checkbox label is to the side of it.

Using flexbox, it doesn’t work because align-items: center; centers it to the entire height including the label:

.wrapper {
  display: flex;
  align-items: center;
}

label span {
  display: block;
}
<div class="wrapper">
  <label>
    <span>label:</span>
    <input type="text">
  </label>
  <label>
    <span>label:</span>
    <input type="text">
  </label>
  <label>
    <input type="checkbox">
    label
  </label>
</div>

But I want the checkbox to be in the center of the text box, something like this:

enter image description here

What is a proper way to achieve this?

2

Answers


  1. Try something like below. I just udpated your align-items property and it looks same as the picture you shared.

    .wrapper {
       align-items: end;
       display: grid;
       grid-template-columns: repeat(3, 1fr); /* Three columns */
       gap: 10px; /* Gap between grid items */
    }
    
    label span {
      display: block;
      word-break: break-word;
    }
    <div class="wrapper">
      <label>
        <span>label:</span>
        <input type="text">
      </label>
      <label>
        <span>Label: Lorem ipsum is placeholder text commonly used in the graphic...
    </span>
        <input type="text">
      </label>
      <label>
        <input type="checkbox">
        label
      </label>
    </div>

    Let me know if it works for you or not.

    Login or Signup to reply.
  2. a speedy solution for you on this occassion could be to align the items in your flex box layout at flex-end instead. Of course, as suggested in other comments, this might not be scalable as it depends on what else you intend to add to the form.
    I hope this is what you were trying to do and I haven’t misunderstood. Happy coding!

    .wrapper {
        display: flex;
        align-items: flex-end;
    }
    
    label span {
         display: block;
    }
    <div class="wrapper">
      <label>
        <span>label:</span>
        <input type="text">
      </label>
      <label>
        <span>label:</span>
        <input type="text">
      </label>
      <label>
        <input type="checkbox">
        label
      </label>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search