Search code examples
htmlcsslabelline-breaks

How to display a label having text with line breaks?


I put text in a <textarea> like this:

First day
1-one apple.
2-one orange.
3-two cups of milk.

But it shows in a <label> like this:

First day 1- one apple. 2-one orange. 3- two cups of milks.

How do I make it look the same as in a <textarea>?


Solution

  • Give the label white-space: pre-wrap and it will break line as the text area does

    textarea {
      height: 70px;
    }
    label {
      white-space: pre-wrap;
    }
    <textarea>
      First day
    1-one apple.
    2-one orange.
    3-two cups of milk.
    </textarea>
    
    <br><br>
    
    <label>
      First day
    1-one apple.
    2-one orange.
    3-two cups of milk.
    </label>


    Besides the white-space property combined with a new line character (e.g. \n), the HTML way to break line is using <br>, add here is a small sample how they work and differ.

    Note, even space's are preserved using e.g. white-space: pre, as seen in the "inline" code sample

    var sample_script = document.querySelector('.sample.script');
    
    var name = "One Two Three";
    var name1 = name.replace(/ /g, '\n');
    var name2 = name.replace(/ /g, '<br>');
    
    sample_script.innerHTML += name1;
    sample_script.innerHTML += "<br><br>";
    sample_script.innerHTML += name2;
    div.pre {
      white-space: pre;
    }
    
    
    /*  styling for this demo  */
    body {display: flex;}
    .sample {flex: 1; margin: 0 20px;}
    <div class="sample inline">
    
      Inline
      <hr>
      <div>
        One
        Two
        Three
      </div>
    
      <div class="pre">
        One
        Two
        Three
      </div>
    </div>
    
    <div class="sample script">
      Script
      <hr>
    
    </div>