I was creating a dropdown menu in ReactJs to select country code. The dropdown consists of country code and country name. I want that the dropdown’s width should be equal to the country code only.
I have given width: max-content to select element.
Here is the code for the same. I am doing styling using tailwind CSS.
<div className="flex gap-6 flex-col mt-4 text-[#2c3345] font-semibold">
<label htmlFor="phone">
Phone Number <span className=" text-red-600">*</span>
</label>
<div className="flex gap-2 items-center text-[#2c3345] font-semibold">
<select
name="dropdown"
id="dropdown"
className="w-max-content py-2"
>
{countryCode.map((element, index) => (
<option key={index} value={element.code}>
{element.code} - {element.country}
</option>
))}
</select>
<input
type="tel"
name="phone"
id="phone"
required
onClick={() => selectHandler("phone")}
className={`bg-transparent outline-none border-b-2 ${
selectedLink === "phone"
? "border-[#4065fa]"
: "border-[#555959]"
} `}
/>
</div>
</div>
Current Output :-
And here is the current output
I want that the width of the dropdown should be equal to the width of country code only.
Desired output:
2
Answers
Since the parent element of both the dropdown (
select
) andinput
components has theflex
class, this means that the 2 children are now flex items.To make the dropdown take only as much space as needed, you can make the
input
element take up all the available space inside the flex container, which you can achieve by adding thegrow
Tailwind (TW) class (equivalent toflex-grow: 1;
) in theinput
element.I would also suggest adding the
shrink-0
TW class (equivalent toflex-shrink: 0;
) in theclassName
field of theselect
element, which will make the dropdown element take as much space as it needs, but will not allow it to shrink more so as to make more room for theinput
element (will not break in a new line in this example).Ultimately, your structure should resemble something like this:
Links:
grow
TailwindCSSshrink-0
TailwindCSSTo change the width of the dropdown according to the selected country code, you can dynamically adjust the width of the select element based on the length of the country code.