user2257652
user2257652

Reputation: 39

Vertically centering icons and searchbox in a navbar

I have been struggling with how to do this reasonably - I need a navbar consisting of an icon on both sides and an expanding searchbox between them. As I achieve this, I can't use display: table-cell on the divs correctly and therefore can't vertically align them better than I have now (using paddings and margins with em's - not quite a viable option). Could anyone help?

Here's a fiddle: http://jsfiddle.net/65brxnb2/

HTML:

<nav class="navbar navbar-fixed-top">
<div class="formline">
    <div id="settingsicondiv"><i class="fa fa-gear fa-2x"></i>
    </div>
    <div id="searchicondiv"><i class="fa fa-search fa-2x"></i>
    </div>
    <div id="searchboxdiv">
        <input class="form-control" type="text" placeholder="Search"></input>
    </div>
</div>

CSS:

nav {
    width: 100%;
    background-color: gray;
    padding-top: 0.5em;
    text-align: center;
}
.formline {
    max-width: 40em;
    margin: 0 auto;
}
input {
    width: 100%;
    font-size: 16px;
}
.fa {
    color: white;
    margin-left: 0.3em;
    margin-right: 0.3em;
    margin-top: 0.15em;
}
#settingsicondiv {
    float:left;
}
#searchicondiv {
    float:right;
}
#searchboxdiv {
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
}

Upvotes: 0

Views: 875

Answers (1)

Fahad Hasan
Fahad Hasan

Reputation: 10506

Simplest way is to set the display property of all your 3 <div>'s to inline-block and then align them vertically in the middle using vertical-align: middle. I also modified your HTML structure just a little bit by placing <div id="searchboxdiv"> before <div id="searchicondiv">.

nav {
  width: 100%;
  background-color: gray;
  padding-top: 0.5em;
  text-align: center;
}
input {
  width: 100%;
  font-size: 16px;
}
.fa {
  color: white;
}
#searchboxdiv {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
div#settingsicondiv,
#searchboxdiv,
#searchicondiv {
  display: inline-block;
  vertical-align: middle;
}
div#searchboxdiv {
width: 50%;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>
<link href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.css" rel="stylesheet"/>
<nav class="navbar navbar-fixed-top">
  <div class="formline">
    <div id="settingsicondiv"><i class="fa fa-gear fa-2x"></i>

    </div>
    <div id="searchboxdiv">
      <input class="form-control" type="text" placeholder="Search"></input>
    </div>
    <div id="searchicondiv"><i class="fa fa-search fa-2x"></i>

    </div>
  </div>
</nav>

Upvotes: 1

Related Questions