Olle burman
Olle burman

Reputation: 31

Resize width of select-element by width of sibling element

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

Is it possible to solve this with pure CSS only?

<!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, only the select-element should shrink/grow in size.

Upvotes: 1

Views: 261

Answers (2)

Mr_Green
Mr_Green

Reputation: 41832

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>

Upvotes: 1

Jleibham
Jleibham

Reputation: 530

Flexbox would work well for this but couldn't you just set the select to a percentage and then the inputs to half of that percentage?

* {
  box-sizing: border-box;
}
.select-container {
  width: 100%;
  }
select {
  width: 100%;
}

input {
  width: 49%;
}
<!DOCTYPE html>
<html>
<body>
<div class="select-container" 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>

Upvotes: 0

Related Questions