Olle burman Olle burman - 1 month ago 9
CSS Question

Resize width of select-element by width of sibling element

I have a problem of setting the width of an select-element (html). The problem can be broken down to 2 parts:


  • The select-element's width = total width of the 2 input-elements.

  • When the width of one of the input-elements is changed = width of select-element is automatically adjusted.



Is it possible to solve this with pure CSS?



<!DOCTYPE html>
<html>
<body>
<div style="display: inline-block; background: blue;">

<select>
<option value="volvo">Volvo Volvo Volvo Volvo Volvo Volvo </option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
</div>
<br>

<input size="8" type="text" value="hej">
<input size="8" type="text" value="hej">

</div>

</body>
</html>





edit
Note that the input-elements has attribute 'size="8"'. I want them to of that size since the rest of the project have that look. Therefore should only the select-element shrink/grow in size.

Answer

Something like this?

What I did is placed the two input elements as sibling to the select tag. and made the select tag position absolute with respect to its parent i.e div. This works only when we know / can control the height of the select tag.

I applied padding-top to div which must be equal to the select tag's height.

select {
  width: 100%;
  display: block;
  position: absolute;
  height: 30px;
  top: 0px;
}
div {
  position: relative;
  padding-top: 30px;
}
<!DOCTYPE html>
<html>
<body>
  <div style="display: inline-block; background: blue;">
    <select>
      <option value="volvo">Volvo Volvo Volvo Volvo Volvo Volvo</option>
      <option value="saab">Saab</option>
      <option value="opel">Opel</option>
      <option value="audi">Audi</option>
    </select>
    <input size="8" type="text" value="hej">
    <input size="8" type="text" value="hej">
  </div>
  <br>
  </div>
</body>
</html>

Comments