Idan Bachar
Idan Bachar

Reputation: 11

Trying to center navbar

I start to learn css in the last week, now im trying to make a nav bar. Im trying to position it in the center but want the background will take 100% of the page.

navbar screenshot

Here's my code:

a {
  font-size: 16px;
  text-decoration: none;
}

.navarea {
  background-color: brown;
}

.navarea:after {
  content: '';
  clear: both;
  display: block;
}

.navarea ul {
  list-style: none;
  margin: 0;
}

.navarea>ul>li {
  float: left;
  position: relative;
}

.navarea ul li a {
  text-decoration: none;
  color: white;
  padding: 15px 20px;
  display: block;
}

.navarea ul li:hover a {
  background-color: cadetblue;
}

.navarea ul ul {
  position: absolute;
  display: none;
  padding: 0;
  min-width: 160px;
  top: 100%;
  left: 0%;
}

.navarea ul li:hover>ul {
  display: block;
}

.navarea ul ul li:hover a {
  background-color: darkgoldenrod;
}

Upvotes: 1

Views: 49

Answers (1)

tacoshy
tacoshy

Reputation: 13001

The modern standard approach (since 2015) is to use Flexbox instead of the float hack. float is intended to be used to float images withing paragraphs. Every other use can be considered a hack and is not necessary since 2012 with the introduction of Grid and Flexbox (which is well supported since 2015).

Use flex-direction: row; to line them up horizontally just liek float. To center them in the horizontal center you can use: justify-content: center;

body {
  margin: 0;
}

nav {
  background-color: blue;
}

nav ul {
  display: flex;
  flex-direction: row;
  justify-content: center;
  list-style-type: none;
  margin: 0;
}

nav li {
  padding: 10px;
}

nav a {
  color: white;
  text-decoration: none;
}
<nav>
  <ul>
    <li><a href="#">Link 1</a></li>
    <li><a href="#">Link 2</a></li>
    <li><a href="#">Link 3</a></li>
  </ul>
</nav>

Upvotes: 1

Related Questions