0

In this below given code, I am trying to align search box in center of navbar but it doesn't work. How I align search bar in center of navbar:

#navbar {
  width: 100%;
  height: 50px;
  background-color: aqua;
}

a {
  text-decoration: none;
  color: black;
  font-size: 1.3em;
}

#search {
  display: inline-block;
  margin: 0 auto;
}

#faviorites {
  float: right;
}
<nav id="navbar">
  <a id="home" href="/">Home</a>
  <input type="text" id="search" placeholder="Search Here">
  <a href="fav.html" id="faviorites">Faviorites</a>
</nav>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Mohit Garg
  • 25
  • 6
  • @Amaresh S M answer is not accurate. it stretches the search bar. Also there's no need to have floats when flexbox is used. I have cleaned up your css and added a better solution and example Fiddle. – Becky Sep 24 '20 at 07:12

3 Answers3

1

Just add display:flex; to #navbar.

#navbar {
  width: 100%;
  height: 50px;
  display:flex;
  background-color: aqua;
}

a {
  text-decoration: none;
  color: black;
  font-size: 1.3em;
}

#search {
  display: inline-block;
  margin: 0 auto;
}

#faviorites {
  float: right;
}
<nav id="navbar">
  <a id="home" href="/">Home</a>
  <input type="text" id="search" placeholder="Search Here">
  <a href="fav.html" id="faviorites">Faviorites</a>
</nav>

if you want to center both horizontally and vertically use:

#navbar {
  width: 100%;
  height: 50px;
  display:flex;
  justify-content:center;
  align-items:center;
  background-color: aqua;
}
Amaresh S M
  • 2,936
  • 2
  • 13
  • 25
0

Easiest way is to use a flexbox and define space-between for horizontal spacing.

#navbar {
  width: 100%;
  height: 50px;
  background-color: aqua;
  display: flex;
  justify-content: space-between;
}

a {
  text-decoration: none;
  color: black;
  font-size: 1.3em;
}
<nav id="navbar">
  <a id="home" href="/">Home</a>
  <input type="text" id="search" placeholder="Search Here">
  <a href="fav.html" id="faviorites">Faviorites</a>
</nav>
Gerard
  • 15,418
  • 5
  • 30
  • 52
0

You can do it easily using flexbox

Add these 3 to your #navbar and that's all needed.

#navbar {
   display: flex;
   justify-content: space-between;
   align-items: flex-start;
   /*your current styles*/
}

jsFiddle

Becky
  • 5,467
  • 9
  • 40
  • 73