Get a form to respect the flexbox of the parent div

I have a form with one input tag sitting inside a div . I am trying to use form / input for the width of the parent, but I cannot make it respond to flexbox - it just solves its own width and overflows the container.

HTML

 <div class="container"> <span>foo</span> <span>bar</span> <form> <input value="baz"/> </form> </div> 

CSS

 .container { display: flex; width: 150px; border: 1px solid black; } 

Screenshot

Screenshot

JSFiddle .

What I would expect is that the flexbox parameter on the parent div will reduce the shape to fit the width, but this does not happen. Instead, form / input just sits with the right width and doesn't compress, even if I install flex-shrink on it.

0
source share
2 answers

try it

 .container { display: flex; width: 150px; border: 1px solid black; } form input{ width: 100%; box-sizing: border-box; } 
 <div class="container"> <span>foo</span> <span>bar</span> <form> <input value="baz"> </form> </div> 
+1
source

If you add this rule, the input setting will be changed.

 .container input { width: 100%; /* override its defalt width */ box-sizing: border-box; /* make border/padding size be included in the set width */ } 

 .container { display: flex; width: 150px; border: 1px solid black; } .container input { width: 100%; /* override its defalt width */ box-sizing: border-box; /* make border/padding size be included in the set width */ } 
 <div class="container"> <span>foo</span> <span>bar</span> <form> <input value="baz" /> </form> </div> 

The reason is that the flex element (here form ) cannot be smaller than its contents, even if it allows compression with flex-shrink .

In this case, it is input , which has a predefined width, and therefore forces a form size with it, where the solution is to override the width of the input .

In addition, since input not a flexible element, the form is, it will not meet the properties of flexible elements.

Flex / flex container elements have a parent / child relationship, and only children are flexible elements, not grandchildren.

Below is a more detailed description of flexible containers / elements and form elements:

+2
source

Source: https://habr.com/ru/post/1264641/


All Articles