简体   繁体   English

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

[英]How to make input to take all remaining width in flex container?

I'm trying to create a simple numeric selector that will be used for mobile and desktop users. 我正在尝试创建一个将用于移动和桌面用户的简单数字选择器 My idea is to have an input surrounded by "plus" and "minus" buttons. 我的想法是使输入由“加号”和“减号”按钮包围。

Everything works fine except the responsiveness of the input field. 除了输入字段的响应能力之外,其他所有东西都工作正常。 Somehow, it doesn't shrink to the container remaining size. 不知何故,它不会缩小到容器的剩余大小。

So, what I would like to have is fixed-size spans ( 2 rem in my case) around the input that takes all the remaining width of the container. 因此,我想在输入周围采用固定大小的跨度(在我的情况下为2 rem ),该跨度占用容器的所有剩余宽度。

Here is the code: 这是代码:

 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> 

I've created a layout that uses flexbox but input doesn't shrink and overflows the container. 我创建了一个使用flexbox的布局,但是输入不会缩小并且不会溢出容器。

Is it possible to make an input to shrink to take all available container width without overflowing container on X axis? 是否可以使输入缩小以占据所有可用的容器宽度而不会在X轴上溢出容器?

You can try this: 您可以尝试以下方法:

 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> 

Your issue can be fixed if you add width property to input element with calc() method in its value. 如果使用calc()方法将width属性添加到输入元素中,则可以解决此问题。 Try this code. 试试这个代码。

input {
    font-size: 2rem;
    margin: 0 10px;
    width: calc(100% - 4rem - 32px);
}

I collected this css property from your codepen link. 我从您的Codepen链接中收集了此CSS属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM