Saturn
Saturn

Reputation: 18139

Center menu items in responsive navbar

w3schools has a nice example of a nav bar that will respond to a smaller screen:

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_topnav

How can I have the menu items centered, instead of aligned to the left? Setting ul.topnav li {float: center;} just makes them stack vertically.

Upvotes: 1

Views: 423

Answers (3)

pjk_ok
pjk_ok

Reputation: 947

You can do this easily with flexbox.

On the link you've given to the W3 site remove the following line:

ul.topnav li {float: left;}  /*remove this line of CSS*/

Then, add the following CSS to the ul.topnav at the top of the page

 ul.topnav {
  display: flex;
  justify-content: center;

  // rest of CSS goes here

}

Upvotes: 1

Ninjabin
Ninjabin

Reputation: 97

float: center; is not valid in CSS, if you want to know more about floats I recommend taking a look at the "CSS layout - float and clear" documentation on the W3C: https://www.w3schools.com/css/css_float.asp

To align the li to the centre of the navigation you could do something like:

ul.topnav {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  text-align: center;
}

ul.topnav li {
  display: inline-block
}

You could also try a more flexbox approach and just have:

ul.topnav {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  display: flex;
  justify-content: center;
}

if you decide to use flexbox you won't need to add: ul.topnav li { display:inline-block; }

Flexbox is well supported nowadays: http://caniuse.com/#feat=flexbox

Upvotes: 2

L L
L L

Reputation: 1470

Try editing the css like this:

ul.topnav {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  text-align:center;
}

here we are just adding centered text alignment. Next

ul.topnav li {display:inline-block;}

Here we are removing the fload:left and setting the display to inline-block. Does this create the desired results for you?

Upvotes: 0

Related Questions