Search code examples
htmlcsswidth

input with labels in content box remaining width


I'm having some troubles with my styling of my custom content box. The content box contains of a few label and input fields. The content box has a width of `500px.

Some of the labels are longer than others, however the input should always be as big as the windows (- a bit of white space).

This is the HTML I have right now:

<div class="content">
    <div class="row">
        <label for="test1">This is a test #1</label>
        <input type="text" name="test1">
    </div>
    <div class="row">
        <label for="test2">This is a test #2</label>
        <input type="text" name="test2">
    </div>
    <div class="row">
        <label for="test3">But this is a test with a much longer label</label>
        <input type="text" name="test3">
    </div>
</div>

And this is the CSS:

.content {
    border: 1px solid #000;
    width: 500px;
    height: 500px;
}

.row {
    margin-top: 5px;
}

input {
    width: 385px;
}

As seen in the fiddle here: https://jsfiddle.net/4ga3533o/ you can see that the first 2 'rows' work correctly, however by the third one, the input is below the label because the width is longer than the content box, how can I get it to work so the labels can have different lengths but the width only takes up the remaining space of the width?


Solution

  • display: flex would be the best solution for your issue. Try this code.

    <div class="content">
      <div class="form-wrap">
        <label for="test1">This is a test #1</label>
        <input type="text" name="test1">
      </div>
      <div class="form-wrap">
        <label for="test2">This is a test #2</label>
        <input type="text" name="test2">
      </div>
      <div class="form-wrap">
        <label for="test3">But this is a test with a much longer label</label>
        <input type="text" name="test3">
      </div>
    </div>
    
    .content {
      border: 1px solid #000;
      width: 500px;
      height: 500px;
    }
    
    .row {
      margin-top: 5px;
    }
    
    input {
      width: 385px;
    }
    
    .form-wrap {
      margin-bottom: 10px;
      display: flex;
      align-items: flex-start;
    }
    
    .form-wrap label {
      width: 40%;
    }