Topic: How to use width: auto on select

sdpollack premium asked 1 year ago

I want to use width: auto on a select so that the width of the select will be determined by the largest item in the options. Is there a way to do this?

<div class="form-group">
 <select id="DayOfWeek" name="DayOfWeek" class="select mx-2" style="width: auto;">
        <option selected="selected" value="0">Sunday</option>
        <option value="1">Monday</option>

Kamila Pieńkowska staff answered 1 year ago

You can do that but not with simple CSS.

Your select would have to look something like that:

<section class="d-flex">
<!-- set width to this div -->
  <div class="width: 200px">
    <select class="select">
      <option value="1">One</option>
      <option value="2">Two</option>
      <option value="3">Three</option>
      <option value="4">Four</option>
      <option value="5">Five</option>
      <option value="6">Six</option>
      <option value="7">Seven</option>
      <option value="8">Eight</option>

and you would have to write JS code that will calculate the width of the widest option and set it (with some additional width for padding and arrow) to div that I've marked above. It can result in some page shifting on initial loading.

sdpollack premium commented 1 year ago

Thanks. I was hoping for a simpler way, but I understand. Given that my list of options is static, I ended up picking a static width that will work.

Please insert min. 20 characters.


Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.



Specification of the issue

  • ForumUser: Premium
  • Premium support: Yes
  • Technology: MDB Standard
  • MDB Version: MDB5 6.2.0
  • Device: PC
  • Browser: Chrome
  • OS: Win 10
  • Provided sample code: No
  • Provided link: No