Search code examples
htmlcssformsinputline-breaks

How to break words on an input field so it starts a new line once the width of the field is reached?


.form-container {
  float: left;
  width: 100%;
}

.form-container input[type=text] {
  padding-bottom: 40px;
  overflow-y: auto;
  overflow-wrap: break-word;
}
    <form class="form-container">
      First name:<br>
      <input type="text" name="firstname" value="Mickey">
      <br>
      Last name:<br>
      <input type="text" name="lastname" value="Mouse">
      <br><br>
      <input type="submit" value="Submit">
    </form>

I need to use an input field, and not a textarea, and I would like the words to break once the width of the input field is reached. At the moment all is written in the same line.

Find below the code that I've been trying.

Thanks in advance for helping this newbie!

.form-container {
  float: left;
  width: 100%;
}

.form-container input[type=text] {
  padding-bottom: 40px;
  overflow-y: auto;
  overflow-wrap: break-word;
}
    <form class="form-container">
      First name:<br>
      <input type="text" name="firstname" value="Mickey">
      <br>
      Last name:<br>
      <input type="text" name="lastname" value="Mouse">
      <br><br>
      <input type="submit" value="Submit">
    </form>

Solution

  • const mickey = document.querySelector('#firstname').textContent;
    .form-container {
      float: left;
      width: 100%;
    }
    
    #firstname {
      padding-bottom: 40px;
      max-width: 60px;
      overflow-y: auto;
      overflow-wrap: break-word;
      border: 1px solid black;
    }
        <form class="form-container">
          First name:<br>
          <div id="firstname" contenteditable="true">Mickey</div>
          <br>
          Last name:<br>
          <input type="text" name="lastname" value="Mouse">
          <br><br>
          <input type="button" value="Submit" onclick="console.log(mickey);">
        </form>

    You can't do that to an input text field, but a contenteditable div can surely help. But be careful when making something which takes up the value from div as it makes some unintented consequences. I tried returning the value from div but it won't return the real value, so here, you are on your own!