The problem is that Flexbox doesn't work in rows/columns the way a Table does. You can use col-sm-auto
to get each label to shrink-to-fit, but then the labels/inputs won't align vertically down the page...
It sounds like you want to shrink the label column to fit the width of the widest label. This could be done by putting all the labels in 1 column, and inputs in another column, but then each label/input won't stack together on mobile screens.
There's no elegant Bootstrap-only solution to this problem. You can use Tables, CSS grid, or the option described by @Toan Lu in the comments.
Bootstrap Grid option
I'd recommend simply using col-sm-2
or col-sm-3
for the labels (fitting them to approx. the widest label) and text-truncate
to ellipsis(...) the overflowing text until they stack vertically on mobile...
<div class="form-row">
<label class="col-form-label col-sm-2 text-truncate">
Label
</label>
<div class="col-sm-3 col-md-2">
<select>..</select>
</div>
</div>
https://codeply.com/go/e3mDrmMv7k
Table option
With this option, the width:1%
is used on the labels so that they shrink to the width of the widest. Use text-nowrap
to stop the labels from wrapping. Each form row is a d-table-row
and each label is a d-table-cell
...
.col-form-label.d-sm-table-cell {
width: 1%;
}
<div class="container py-3">
<div class="form-row d-table-row">
<label class="col-form-label col-sm-2 d-sm-table-cell text-nowrap">
Genre
</label>
<div class="col-sm-3 col-md-2">
<select>
..
</select>
</div>
</div>
<div class="form-row d-table-row">
<label class="col-form-label col-sm-2 d-sm-table-cell text-nowrap">
Longer label here
</label>
<div class="col-sm-3 col-md-2">
<select>
..
</select>
</div>
</div>
</div>
https://codeply.com/go/e3mDrmMv7k (see 2nd option)
The table option makes the divs into tr/td but also works responsively allowing the fields to stack vertically on mobile. Read more on [d-table classes](Yes, part of Bootstrap 4: http://getbootstrap.com/docs/4.1/utilities/display/#notation).
CSS Grid option
One other (non-Bootstrap 4) method is using CSS grid. Make the row display:grid
Use the fr
sizing on the 2 grid-template-columns
across the row.
.d-grid {
display: grid;
grid-template-columns: 0fr 1fr;
}
https://codeply.com/go/9Z7Hg2tl1H
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…