To optimize your setup, I suggest enclosing each input
and label
pair in a container div
. Utilize the existing d-flex
class on your btn-group
by leveraging flex properties.
In your CSS, target the btn-container
divs and assign them a flex-basis: 100px
(adjust pixel value as needed) for consistent width. Alternatively, use percentage values like flex-basis: 25%
for even distribution with multiple buttons.
.d-flex {
display: flex;
}
.btn-container {
flex-basis: 100px;
}
<link href="https://cdn.bootstrap.css" rel="stylesheet"/>
<div class="d-flex btn-group" role="group" aria-label="Basic radio toggle button group">
<div class="btn-container">
<input type="radio" class="btn-check" name="btnradio" id="btnradio1" autocomplete="off" checked/>
<label class="btn btn-outline-primary" for="btnradio1">Text</label>
</div>
<div class="btn-container">
<input type="radio" class="btn-check" name="btnradio" id="btnradio2" autocomplete="off"/>
<label class="btn btn-outline-primary" for="btnradio2">More Text</label>
</div>
</div>
If you're hiding the radio input and displaying only the labels, consider this approach:
.d-flex {
display: flex
}
input {
position: absolute;
width: 0.01px;
}
label {
border: 1px solid black;
padding: 1rem 2rem;
flex-basis: 50%;
}
input:checked + label {
background-color: blue;
}
<div class="d-flex btn-group" role="group" aria-label="Basic radio toggle button group">
<input type="radio" class="btn-check" name="btnradio" id="btnradio1" autocomplete="off">
<label class="btn btn-outline-primary" for="btnradio1">Text</label>
<input type="radio" class="btn-check" name="btnradio" id="btnradio2" autocomplete="off">
<label class="btn btn-outline-primary" for="btnradio2">More Text</label>
</div>
If you're using bootstrap, skip the extra styling on the btn group and focus on adding flex basis to the label.