css 添加输入时,Div会扩展

kh212irz  于 2023-04-13  发布在  其他
关注(0)|答案(3)|浏览(115)

当添加一个新的输入字段时,字段块的宽度每次都会增加。如果不指定字段块的宽度,我如何解决这个问题?

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>
rt4zxlrg

rt4zxlrg1#

如果不想修改inputwidth,可以flex#fields容器并指定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>
brqmpdu1

brqmpdu12#

使用display: block代替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>
t2a7ltrp

t2a7ltrp3#

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>

相关问题