MeltingDog MeltingDog - 17 days ago 7
CSS Question

Way to negate a number of pixels from and element with width 100%?

I have a simple search form:

<div class="search">
<input placeholder="Search term here">
<button>
Go
</button>
</div>


Naturally, the button goes to the right of the input. However, on mobile devices, I want to reverse this - to have the button on the left.

To that effect I have created:

.search {
width: 100%;
}

input {
float: right;
width: 100%;
height: 30px;
}

button {
float: left;
width: 30px;
height: 30px;
}


https://jsfiddle.net/ufLoj5se/5/

But of course this pushes the button on to a 2nd line.

Is there a way to negate the 30px width of the button from the input to allow the button to sit snugly on the left?

Answer

Instead of juggling around floats, you could use flex-box.

You could position your elements any where you need, more precisely depending on your screen resolution.

Here is what you could do.

.search {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
}
input {
  width: 100%;
  height: 30px;
  order: 1;
}
button {
  width: 30px;
  height: 30px;
  order: 2;
}
@media only screen and (max-width: 480px) {
  button {
    order: 1;
  }
  input {
    order: 2;
  }
}
<div class="search">
  <input placeholder="Search term here">
  <button>
    Go
  </button>
</div>