Search code examples
htmlcsscarriage-return

Line break after input using only css


I got a html with a lot of label + input

<label>Application</label>
<input id="ApplicationName" />
...
<label>Foo</label>
<input id="Foo" />
...
<label>Junk</label>
<input id="Junk" />

I force a width to add some consistency

label {
    display: inline-block;
    width: 10em;
}
input {
    width: 10em;
}

With this style it's a bit better but the flow still breaks "anywhere" depending on the width of container. How can I make the label + input to be a block ? (Without enclosing both of them in a container)

Another acceptable solution would be to
add a virtual carriage return after each input or
before each label.
I didn't succeed to put it after because the input tag doesn't support after.
Neither can I put it before because

label::before {
    content: "\A";
    white-space: pre;
}

doesn't mix well with label{display:inline-block}

label {
    display:inline-block;
    width:10em;
}

input {
    width:10em;
}
<div>
    <label>namespace</label>
    <input id="namespace" />
            
    <label>Application</label>
    <input id="application" />
            
    <label>Description</label>
    <input id="Description" />
            
    <label>Author</label>
    <input id="Author" />
</div>
resize the window to exhibit unwanted behaviour


Solution

  • You can use a mixture of floating and clearing, a bit old school but seems to work for the structure:

    label {
      display: block;
      width: 10em;
      float: left; /* makes the element act like inline block */
      clear: left; /* clears any left floats so before so this should start on new line */
    }
    
    input {
      width: 10em;
      float: left;
    }
    <div>
      <label>namespace</label>
      <input id="namespace" />
    
      <label>Application</label>
      <input id="application" />
    
      <label>Description</label>
      <input id="Description" />
    
      <label>Author</label>
      <input id="Author" />
    </div>

    Or you could just give a width to your parent container to force the content onto the next line:

    div {
      width: 21em;
    }
    
    label {
      display: inline-block;
      width: 10em;
    }
    
    input {
      width: 10em;
    }
    <div>
      <label>namespace</label>
      <input id="namespace" />
    
      <label>Application</label>
      <input id="application" />
    
      <label>Description</label>
      <input id="Description" />
    
      <label>Author</label>
      <input id="Author" />
    </div>