2016-12-05 43 views
3

好吧,我對flex的表現不是很好,因爲我沒有使用它,但我認爲沒有其他方法可以做到這一點。我想製作一個簡單的表格,它的右側會標註說明和輸入。此描述可以具有任何大小和輸入將增加其大小以滿足父項。下面是代碼:在flexbox內部製作元素的動態寬度

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>

它不應該是這樣的:

enter image description here

+0

可能bootstra p input-group-addon也可以幫助你。檢查一次https://v4-alpha.getbootstrap.com/components/input-group/ –

+0

這將是更多的工作來擺脫所有這些風格(背景,填充,邊界...)。無論如何,我使用基礎,所以會有衝突。 – debute

回答

4

你只需要的label柔性屬性設置爲:flex: 0 1 auto。這意味着:flex-grow: 0flex-shrink: 1flex-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>

+0

現在有多容易:)謝謝! – debute

+1

不客氣!祝你的項目好運。 –

1

只需添加柔性以標籤和輸入標籤 看到這裏http://codepen.io/tantata/pen/KNoMWQ

div { 
 
    display: flex; 
 
    width: 300px; 
 
    margin-bottom: 20px; 
 
    border: 1px solid red; 
 
    flex-wrap:nowrap; 
 
} 
 
label { 
 
    height: 21px; 
 
    line-height: 21px; 
 
    font-size: 14px; 
 
    color: black; 
 
    flex-grow: 0; 
 
} 
 
input { 
 
    margin-left: 20px; 
 
    flex-grow: 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>