Search code examples
htmlcssreactjsstyling

Vertically align input tags in css


So i have a container with a wrapper inside and inside that is a h1 tag and a form and I want to align all the input tags and the h1 tag from where the tags start and put the labels to the left of them. Like this for example:

         exampleName
    name []
username []

Here is what I have tried

.edit_profile_user_container {
  width: 70%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.edit_profile_user_wrapper {
  width: 90%;
  height: 90%;
  vertical-align: baseline;
}

.edit_profile_user_info {
  height: 10%;
  width: 100%;
}

.edit_profile_user_form {
  height: 90%;
  width: 100%;
  border: none;
}
<div className='edit_profile_user_container'>
  <div className='edit_profile_user_wrapper'>
    <div className='edit_profile_user_info'>
      <p>username</p>
    </div>
    <form className='edit_profile_user_form'>
      <div className='edit_profile_input_section'>
        <label for="name">Name</label>
        <input type="text" name="name" />
      </div>
      <div className='edit_profile_input_section'>
        <label for="username">Username</label>
        <input type="text" name="username" />
      </div>
    </form>
  </div>
</div>


Solution

  • Here's a way to do it, minimal markup, using display: grid:

    .form-container {
      display: grid;
      grid-template-columns: 10rem auto;
      grid-gap: .3rem;
    }
    
    .form-container label {
      grid-column: 1;
      text-align: right;
    }
    
    .form-container label::after {
      content: ':';
    }
    
    .form-container h1 {
      grid-area: 1/2/2/3;
    }
    
    .form-container h1 + label {
      grid-row: 2;
    }
    
    .form-container input {
      grid-column: 2;
    }
    
    .form-container label, .form-container input {
      padding: .3rem .5rem;
    }
    <div class='form-container'>
      <h1>exampleName</h1>
      <label for="name">Name</label>
      <input id="name" />
      <label for="username">Username</label>
      <input id="username" />
    </div>

    Equivalent SCSS:

    .form-container {
      display: grid;
      grid-template-columns: 10rem auto;
      grid-gap: .3rem;
      label {
        grid-column: 1;
        text-align: right;
        &::after {
          content: ':';
        }
      }
      h1 {
        grid-area: 1/2/2/3;
        + label {
          grid-row: 2;
        }
      }
      input {
        grid-column: 2;
      }
      & label, & input {
        padding: .3rem .5rem;
      }
    }
    

    Note: you can reduce the CSS by adding an empty element before the <h1>. Demo.