如何使输入框在flex容器中占据所有剩余的宽度?

3
我正在尝试创建一个简单的数字选择器,将用于移动和桌面用户。我的想法是在输入框周围放置“加”和“减”按钮。
一切都很好,除了输入框的响应性。不知何故,它不会缩小到容器剩余的大小。
因此,我想要的是固定大小的span(在我的情况下为2rem),围绕着输入框,占据容器的所有剩余宽度。
以下是代码:

body {
  background: #f5f5f5;
}

.outer-container {
  width: 300px;
  border: 1px solid gray;
  padding: 10px;
}

.container {
  display: inline-flex;
  align-items: center;
}

.item {
  dsipaly: inline-block;
  height: 2rem;
  width: 2rem;
  font-size: 2rem;
  line-height: 2rem;
  border: 1px solid black;
  border-radius: 50%;
  text-align: center;
}

input {
  font-size: 2rem;
  margin: 0 10px;
}
<div class="outer-container">
  <div class="container">
    <span class="left item">-</span>
    <input type="text" />
    <span class="right item">+</span>
  </div>
</div>

我已经创建了一个使用flexbox的布局,但是输入框不会缩小并且会溢出容器。

有没有可能使输入框在不溢出容器的情况下缩小以占用所有可用的容器宽度?

2个回答

7
你可以尝试这样做:

body {
  background: #f5f5f5;
}

.outer-container {
  width: 300px;
  border: 1px solid gray;
  padding: 10px;
}

.container {
  display: inline-flex;
  align-items: center;
}

.item {
  height: 2rem;
  width: 2rem;
  font-size: 2rem;
  line-height: 2rem;
  border: 1px solid black;
  border-radius: 50%;
  text-align: center;
}

input {
  font-size: 2rem;
  margin: 0 10px;
  min-width:0; /* Remove the automatic minimum size set so the element can shrink*/
  width: 87%; /* Set any value of width here as reference*/
  flex: 1; /* make the item grow to fill the remaining space */
}
<div class="outer-container">
  <div class="container">
    <span class="left item">-</span>
    <input type="text" >
    <span class="right item">+</span>
  </div>
</div>


@Alohci 是的,忘记了最小宽度 ;) 已修复。 - Temani Afif
哇,这看起来真的很有趣。所以,您已经将“input”设置为flex容器本身,因此它占用了所有可用空间,对吗? - WhiteAngel
@WhiteAngel 不是的,我只是给输入框添加了一些属性... 首先你需要将min-width设置为0,因为输入框已经有了最小宽度,然后你让它占据容器的100%宽度,通过设置flex:1,你使其缩小以留出空间给其他元素 ;) - Temani Afif
@WhiteAngel,请查看此链接:https://dev59.com/mVoV5IYBdhLWcg3wc-Ym,以了解有关min-width技巧的更多信息。 - Temani Afif
太棒了!非常感谢!正是我在寻找的东西!干得好!现在一切都清楚了) - WhiteAngel

1
如果您在输入元素中使用calc()方法添加宽度属性,可以解决您的问题。尝试使用以下代码。
input {
    font-size: 2rem;
    margin: 0 10px;
    width: calc(100% - 4rem - 32px);
}

我从您的CodePen链接中收集了这个CSS属性。

谢谢你的解决方案,但是我想避免使用 calc()。对我来说它看起来更像一个黑客,不是吗?难道不能只用 flex-box 来实现吗? - WhiteAngel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接