Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make dynamic width of elements inside of flexbox

Tags:

html

css

flexbox

Well, I'm not good with the flex, because I don't use it a lot, but I think there is no other way how to make this happen. I want to make simple form, which will have label with description and input on its right side. This description can have any size and input would increase its size to fulfill the parent. Here is the code:

div {
    display: flex;
    width: 300px;
    margin-bottom: 20px;
    border: 1px solid red;
}
label {
    height: 21px;
    line-height: 21px;
    font-size: 14px;
    color: black;
    flex: 1;
}
input {
    margin-left: 20px;
    flex: 1;
}
<div>
    <label>Company</label>
    <input type="text">
</div>
<div>
    <label>Street</label>
    <input type="text">
</div>
<div>
    <label>Who are you?</label>
    <input type="text">
</div>

It should looks like this:

enter image description here

like image 877
debute Avatar asked Dec 05 '16 12:12

debute


People also ask

How do I change the width on my flexbox?

A flexbox item can be set to a fixed width by setting 3 CSS properties — flex-basis, flex-grow & flex-shrink. flex-basis : This property specifies the initial length of the flex item. flex-grow : This property specifies how much the flex item will grow relative to the rest of the flex items.

How do I add spacing between elements in flexbox?

To set space between the flexbox you can use the flexbox property justify-content you can also visit all the property in that link. We can use the justify-content property of a flex container to set space between the flexbox.

Can flexbox be nested?

You can create two dimensional layouts by nesting a flex container inside another one. Flexbox is inherently a one dimensional layout model. Flex items within a flex container can be laid out either horizontally or vertically, but not both.


1 Answers

You just have to set the flex property of label to: flex: 0 1 auto. This means: flex-grow: 0, flex-shrink: 1 flex-basis: auto

div {
    display: flex;
    width: 300px;
    margin-bottom: 20px;
    border: 1px solid red;
}
label {
    height: 21px;
    line-height: 21px;
    font-size: 14px;
    color: black;
    flex: 0 1 auto;
}
input {
    margin-left: 20px;
    flex: 1;
}
<div>
    <label>Company</label>
    <input type="text">
</div>
<div>
    <label>Street</label>
    <input type="text">
</div>
<div>
    <label>Who are you?</label>
    <input type="text">
</div>
like image 65
Nico O Avatar answered Oct 26 '22 19:10

Nico O