skip to Main Content

I have a <select> element styled with Bootstrap 5.

<div class="col-md-12">
    <div class="mb-3">
        <label asp-for="Schedule.Minutes" class="control-label"></label>
        <select asp-for="Schedule.Minutes" class="form-control" asp-items="Model.MinutesOptions"></select>
        <span asp-validation-for="Schedule.Minutes" class="text-danger"></span>
    </div>
</div>

I’m using class="form-control" so that it has Bootstrap styling like my other elements. However, by default this causes the element to take up the full available width.

In this case, I’d prefer the element only to be wide enough to accommodate its contents (in this case, the longest list option).

Does Bootstrap provide an option for this?

2

Answers


  1. Chosen as BEST ANSWER

    The answer is to use the w-auto class in addition to form-control.

    <select asp-for="ReportJobSchedule.Subject" class="form-control w-auto" asp-items="Model.MinutesOptions"></select>
    

  2. although Bootstrap utility class w-auto can be used alongside the form-control utility class to achieve this result,
    you can also achieve this by using additional custom styling to make the element only as wide as its contents.

    Here’s an example of how you can achieve this using custom CSS:

    .custom-width-select {
        width: auto !important;
    }
    
    <select asp-for="Schedule.Minutes" class="form-control custom-width-select" asp-items="Model.MinutesOptions">  </select>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search