Create a perfect search bar with CSS Calc

March 6, 2016

This is a neat trick with CSS3’s calc function. Let’s say you’re trying to build a search form and you want the submit button and the text input to float next to each other.

To start off with, let’s just create a simple form:

<form>
  <input class="form-control" type="text" placeholder="Search this site.." />
  <input class="btn btn-primary form-control" type="submit" value="Search" />
</form>

Screen Shot 2016-03-05 at 3.02.11 PM

In the past, the way we get them to float nicely is to assign them each a fluid, percent based, width. Something like:

input[type="text"] {
  width: 70%;
  float: left;
}

input[type="submit"] {
  width: 30%;
  float: left;
}

Which looks pretty good!

Screen Shot 2016-03-05 at 4.04.51 PM

If you do width 70% and 30% there is not guarantee the text will be readable, especially if the button text is long. 30% could well be less width than the text needs.

The Solution

With CSS calc you can give the button a fixed width and give the remaining width to the input. Check this out!

input[type="text"] {
  width: calc(100% - 100px);
  float: left;
}

input[type="submit"] {
  width: 100px;
  float: left;
}

This will keep your button a set width, and grow and shrink the text input as needed!

Screen Shot 2016-03-05 at 8.51.45 PM