This markup contains floating selects inside a bootstrap grid:
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<div class="container w-50 mt-4">
<div class="row">
<div class="col">
<div class="form-floating">
<select class="form-select" id="a">
<option value="" selected=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<label for="a">Foo Bar Baz</label>
</div>
</div>
<div class="col-auto">
<div class="form-floating">
<select class="form-select" id="b">
<option value="" selected=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<label for="b">Spam Ham Eggs</label> <!-- this overflows -->
</div>
</div>
</div>
</div>
Notice how the second column has col-auto
to minimise its width, but then the label overflows the column. I tried overflow-visible
but that doesn't help - because the label is absolutely positioned.
Is there some way to fix this (without hardcoding a width)?
What's causing the problem is that the label
has position: absolute
for the effect. Therefore, the width of the selection container has no relation to the width of the label. Even if both containers used col
, the label would still overflow when the viewport is very narrow.
A hack would be to duplicate the label in a hidden span
so that the width of the selection box won't be less than the width of the label text.
<span class="m-1 invisible">Spam Ham Eggs</span>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<div class="container w-50 mt-4">
<div class="row">
<div class="col">
<div class="form-floating">
<select class="form-select" id="a">
<option value="" selected=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<label for="a">Foo Bar Baz</label>
</div>
</div>
<div class="col-auto">
<div class="form-floating">
<select class="form-select" id="b">
<option value="" selected=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<label for="b">Spam Ham Eggs</label> <!-- this overflows -->
<span class="m-1 invisible">Spam Ham Eggs</span>
</div>
</div>
</div>
</div>