0

I have a text field (input type="text") and a select list. The text field is wider than the select list. They are both in separate rows of a flex box. How can I make the text field the same width as the select list using pure css (no javascript)?

Looks something like this:

<div style="display: flex; flex-direction: column">
  <input type="text">
  <select>
    <option>Tiny</option>
  </select>
</div>

What happens is that the select list grows to the size of the text input (its default size as specified by the browser) rather than the input shrinking to the size of the list.

I apologize if this has been asked before (if so, a link would be appreciated) but so far, I can't find anything that addresses this obvious issue.

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Rex the Strange
  • 133
  • 1
  • 6

2 Answers2

1

You can make the input position:absolute so that the select will specify the width of the container (set to inline-block) and then the input will stretch to this width:

.container {
  display: inline-block;
  position: relative;
}

input {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  box-sizing: border-box;
}

select {
  margin-top: 22px;
}
<div class="container">
  <input type="text">
  <select>
    <option>Tiny</option>
  </select>
</div>

<div class="container">
  <input type="text">
  <select>
    <option>long option</option>
  </select>
</div>

<div class="container">
  <input type="text">
  <select>
    <option>very very long option</option>
  </select>
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • I don't normally like using position absolute unless it's an obvious floating element, like a popup window, but this is the only answer that actually solves the problem. The others are close, they skirt around it, but this hits the nail on the head. You get my upvote. – Rex the Strange Oct 29 '18 at 15:47
-2

A simple solution would be using inline-flex instead of flex:

<div style="display: inline-flex; flex-direction: column">
  <input type="text">
  <select>
    <option>Tiny</option>
  </select>
</div>
Ali Sheikhpour
  • 10,475
  • 5
  • 41
  • 82