rstage rstage - 3 months ago 5
CSS Question

How do I create a fluid single-line form when I don't know the length of the text it contains?

I've got a one-line form that I need to style as follows:
enter image description here


  • Label is left aligned

  • Select box is fluid width

  • Link is right-aligned (with a fixed right margin)



What CSS should I use to keep each of the text fields on one line (bearing in mind the text length might change) and make the select box auto-fill the rest of the space?

Answer

Flexbox can do that

.wrapper {
  display: flex;
  border: 1px solid grey;
  width: 90%;
  margin: 1em auto;
  align-items: center;
}
label {
  padding: 1em;
}
select {
  margin-right: 1em;
  flex: 1;
}
a {
  margin-left: auto;
  margin-right: 50px;
  padding: 0 1em;
  text-decoration: none;
}
<div class="wrapper">
  <label for="">Label</label>
  <select>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </select>
  <a href="#1">Some random text</a> 

</div>

<div class="wrapper">
  <label for="">Label</label>
  <select>
    <option value="mercedes">Mercedes</option>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="audi">Audi</option>
  </select>
  <a href="#1">Some longer random text</a> 

</div>

CSS Table Layout

.wrapper {
  display: table;
  border: 1px solid grey;
  width: 95%;
  margin: 1em auto;
}
label {
  display: table-cell;
  padding: 1em;
  width: 1%;
}
select {
  display: table-cell;
  width: 100%;
  padding-right: 1em;
}
a {
  display: table-cell;
  text-decoration: none;
  width: 1%;
  padding-left: 1em;
  padding-right: 50px;
  white-space: nowrap;
}
<div class="wrapper">
  <label for="">Label</label>
  <select>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </select>
  <a href="#1">Some random text</a> 

</div>

<div class="wrapper">
  <label for="">Label</label>
  <select>
    <option value="mercedes">Mercedes</option>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="audi">Audi</option>
  </select>
  <a href="#1">Some longer random text</a> 

</div>

Comments