skip to Main Content

When adding a new input field, the width of the fields block increases each time.
How can I fix it without specifying the width for the fields block?

setInterval(function() {
  var input = '<input type="text">';
  $("#fields").append(input);

}, 2000);
body {
  background: grey;
  display: flex;
  align-items: center;
  justify-content: center;
}

#fields {
  background: green;
  padding: 20px;
}

#fields input {
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="fields">
  <input type="text">
</div>

3

Answers


  1. Use display: block instead width: 100%:

    setInterval(function() {
      var input = '<input type="text">';
      $("#fields").append(input);
    
    }, 2000);
    body {
      background: grey;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    #fields {
      background: green;
      padding: 20px;
    }
    
    #fields input {
      display: block;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="fields">
      <input type="text">
    </div>
    Login or Signup to reply.
  2. If you do not want to modify the width of input you can flex the #fields container and specify flex-direction: column;.

    setInterval(function() {
      var input = '<input type="text">';
      $("#fields").append(input);
    
    }, 2000);
    body {
      background: grey;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    #fields {
      display: flex;
      flex-direction: column;
      background: green;
      padding: 20px;
    }
    
    #fields input {
      width: 100%;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="fields">
      <input type="text">
    </div>
    Login or Signup to reply.
  3. setInterval(function() {
      var input = '<input type="text">';
      $("#fields").append("<br>"+input);
    
    }, 2000);
    body {
      background: grey;  
    }
    
    #fields {
      background: green;
      padding: 20px;  
      text-align:center;
    }
    
    
    
    #container{
    width:60%;
    border:solid 2px green;
    margin:0 auto;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id='container'>
    <div id="fields">
      <input type="text">
    </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search