CSS:更改子填充会影响父尺寸(框大小:border-box)

时间:2019-09-18 10:45:22

标签: css layout padding

我在应用程序中使用react-bootstrap。考虑这样的布局:

let changed = false
document.querySelector("#addPadding").onclick = () => {
  const elem = document.querySelector('.input')
  elem.style.paddingRight = changed ? 0 : '2rem'
  changed = !changed
}
* {
  box-sizing: border-box;
}

.body {
  /* Width and height are actually unknown,
     set only for presentation purposes */
  width: 600px;
  height: 200px;
  border: 1px solid black;
  
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 2rem;
}

.otherStuff {
  background: aqua;
  margin-right: 2rem;
  max-width: 30%;
}

.form {
  background: palevioletred;
  height: 75%;
  padding: 2rem;
  min-width: 40%;
}

.input {
  width: 100%;
  padding: .2rem;
}
<button id="addPadding">Add padding</button>
<article class="body">
  <div class="otherStuff">Some content of unknown size</div>
  <div class="form">
    <input class="input">
  </div>
</article>

如果运行该代码段,您会注意到,每次输入的填充更改时,父元素的宽度也会更改。并不是所有的视口大小都发生这种情况:例如,如果.body的宽度为400px800px,它就可以正常工作。引导程序会在内部更改填充大小,因此我无法真正影响它。即使我可以,这也会破坏其他内容。我该怎么做才能防止父母在这里伸展?

1 个答案:

答案 0 :(得分:0)

使用width:100%将输入视为弹性项目,而不是flex-grow:1

let changed = false
document.querySelector("#addPadding").onclick = () => {
  const elem = document.querySelector('.input')
  elem.style.paddingRight = changed ? 0 : '2rem'
  changed = !changed
}
* {
  box-sizing: border-box;
}

.body {
  /* Width and height are actually unknown,
     set only for presentation purposes */
  width: 600px;
  height: 200px;
  border: 1px solid black;
  
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 2rem;
}

.otherStuff {
  background: aqua;
  margin-right: 2rem;
  max-width: 30%;
}

.form {
  background: palevioletred;
  height: 75%;
  padding: 2rem;
  min-width: 40%;
  display:flex;
}

.input {
  flex-grow:1;
  width:0;
  align-self:flex-start;
  padding: .2rem;
  
  background:yellow content-box; /* To illustrate */
}
<button id="addPadding">Add padding</button>
<article class="body">
  <div class="otherStuff">Some content of unknown size</div>
  <div class="form">
    <input class="input">
  </div>
</article>