T.XL T.XL - 4 months ago 8
CSS Question

Aligning form labels to the left of inputs

I am trying to move my label tags to the left rather than above in a media query for larger screen size. I have tried:

label {
display:inline-block;
}


I have also turned my container into a flexbox, set it to row, and tried to float the label left, but neither are working.

I am sure there must be a straightforward way to do this and would appreciate your help if you know how. Thank you.

Below is a section of my code.



<div class="container">
<div id="contact-information">
<h2>Contact Information</h2>
<form action="" method="post">
<fieldset input style="border:none">
<div>
<label for="email">Email Address:</label>
<br>
<input type="email" id="email" name="user_email-address" value="" placeholder="Required">
</div>
<div>
<label for="home-number">Home Phone Number:</label>
<br>
<input type="tel" id="home-number" name="user_homeNumber" value="">
</div>
<div>
<label for="mobile-number">Mobile Phone Number:</label>
<br>
<input type="tel" id="mobile-number" name="user_mobileNumber" value="">
</div>
</form>




Answer

/* establish flex container */
form > fieldset > div {
    display: flex;                                      
    margin-bottom: 5px;
}

/* set length of label */
form > fieldset > div > label {
    flex: 0 0 200px;
}

/* tell input to take all remaining width */
form > fieldset > div > input {
    flex: 1;
}

/* media query for smaller screens */
@media ( max-width: 800px ) {

    /* label and input stack vertically */
    form > fieldset > div { flex-direction: column; } 

    /* label takes height based on content */
    form > fieldset > div > label { flex: 0 0 auto; } 
}
<!-- I removed the <br> tags and added </fieldset> to properly close the element -->
<div class="container">
  <div id="contact-information">
    <h2>Contact Information</h2>
    <form action="" method="post">
      <fieldset input style="border:none">
        <div>
          <label for="email">Email Address:</label>
          <input type="email" id="email" name="user_email-address" value="" placeholder="Required">
        </div>
        <div>
          <label for="home-number">Home Phone Number:</label>
          <input type="tel" id="home-number" name="user_homeNumber" value="">
        </div>
        <div>
          <label for="mobile-number">Mobile Phone Number:</label>
          <input type="tel" id="mobile-number" name="user_mobileNumber" value="">
        </div>
      </fieldset>
    </form>
  </div>

jsFiddle