CSS:100% 宽度减去同一行上的元素



如何使输入元素具有 100% 的宽度可用?那么,100% 宽度减去同一行上任何其他元素的宽度(不知道这些元素的宽度)?

.bg {
  padding: 20px;
  background: #f5f5f5;
  margin-bottom: 25px;
 }
input {
  width: 100%;
  padding: 0.4em;
  height: 25px;
  border: 1px solid #ccc;
}
.button {
  height: 25px;
  padding: 0.4em;
  background: #ccc;
  border: 1px solid #ccc;
  text-decoration: none;
 }
<div class="bg">
  
  <input type="text" placeholder="100% width - button" /><a class="button" href="#">Click</a>
  
 </div>
<div class="bg">
  
  <input type="text" placeholder="100% width" />
  
 </div>

有两种

方法可以做到这一点:

  • 使用 flexbox ,在 .bg 中应用display:flex.bg2用于演示)和flex:1(或只是flex-grow:1input

.bg {
  padding: 20px;
  background: #f5f5f5;
  margin-bottom: 25px;
}
.bg2 {
  display: flex;
  border: solid red
}
.bg2 input {
  flex: 1;
}
input {
  width: 100%;
  padding: 0.4em;
  height: 25px;
  border: 1px solid #ccc;
}
.button {
  height: 25px;
  padding: 0.4em;
  background: #ccc;
  border: 1px solid #ccc;
  text-decoration: none;
}
<div class="bg bg2">
  <input type="text" placeholder="100% width - button" /><a class="button" href="#">Click</a>
</div>
<div class="bg">
  <input type="text" placeholder="100% width" />
</div>

  • 对于旧版本的 IE,请使用 CSS 表

* {
  box-sizing: border-box
}
.bg {
  padding: 20px;
  background: #f5f5f5;
  margin-bottom: 25px;
  display: table;
  width: 100%;
}
input {
  display: table-cell;
  width: 100%;
  padding: 0.4em;
  height: 25px;
  border: 1px solid #ccc;
}
.button {
  display: table-cell;
  height: 25px;
  padding: 0.4em;
  background: #ccc;
  border: 1px solid #ccc;
  text-decoration: none;
}
<div class="bg bg2">
  <input type="text" placeholder="100% width - button" /><a class="button" href="#">Click</a>
</div>
<div class="bg">
  <input type="text" placeholder="100% width" />
</div>

display:flex添加到.bg类中即可。Flexbox 尝试均匀分布其子元素,但由于其中一个元素的宽度为 100%,并且还有另一个子元素,因此宽度会进行调整,因此所有元素都适合一行。这里有一个关于弹性属性的很好的指南。

最新更新