Pugly
Pugly

Reputation: 29

How to space out three categories in a navbar evenly

I need to space out my nav bar to four even sections through 1920px I try'd margin-left:25% and doubling it for every li but it didnt look right to me.

li{
float:left;
}

a{
color:#111;

ul{
position:fixed;
}

li a{
display: block;
padding: 14px 16px;
text-decoration: none; 
position:relative;
position:fixed;
}

li a:hover{
background-color: #111;
color: white;
}




 <ul>
 <li><a>Home</a></li>
 <li><a>Sign Up</a></li>
 <li><a>Forum</a></li>
 <li><a>Gallery</a></li>
 </ul>

Upvotes: 1

Views: 113

Answers (4)

Neetigya
Neetigya

Reputation: 121

using flexbox or table display type is an easier and better way but if you are want to learn about what's wrong in your code then

1) there is closing bracket '}' missing

2) set the ul width to 100%.

3) then apply the margin-left property but keep it less because 100/25 = 4, it's just margin, we have not calculated the space that each li would take so somewhere 17% - 18% will spread li's on the screen's top.

4)Remove property "position: fixed" on 'li'

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

It is better to use flexbox for this scenario. It doesn't matter how many elements you have, flexbox manages it all for you:

* {margin: 0; padding: 0; list-style: none;}
a {text-decoration: none; display: block; padding: 5px; border: 1px solid #ccc; color: #000; border-radius: 3px; margin: 3px;}
ul {display: flex;}
ul li {flex-grow: 1; flex-basis: 0;}
<h2>With 4 Columns</h2>
<ul>
  <li><a href="#">Home</a></li>
  <li><a href="#">Sign Up</a></li>
  <li><a href="#">Forum</a></li>
  <li><a href="#">Gallery</a></li>
</ul>
<h2>With 3 Columns</h2>
<ul>
  <li><a href="#">Home</a></li>
  <li><a href="#">Sign Up</a></li>
  <li><a href="#">Forum</a></li>
</ul>
<h2>With 5 Columns</h2>
<ul>
  <li><a href="#">Home</a></li>
  <li><a href="#">Sign Up</a></li>
  <li><a href="#">Forum</a></li>
  <li><a href="#">Gallery</a></li>
  <li><a href="#">Contact</a></li>
</ul>

Preview

preview

Upvotes: 2

Michael Coker
Michael Coker

Reputation: 53674

flexbox does this easily with justify-content: space-between

You can read more about the available options here https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Using_CSS_flexible_boxes

ul {
  display: flex;
  justify-content: space-between;
  padding: 0;
  position: fixed;
  left: 0; right: 0;
}

a {
color:#111;
}

li {
  list-style: none;
}

li a {
display: block;
padding: 14px 16px;
text-decoration: none; 
}

li a:hover{
background-color: #111;
color: white;
}
 <ul>
 <li><a>Home</a></li>
 <li><a>Sign Up</a></li>
 <li><a>Forum</a></li>
 <li><a>Gallery</a></li>
 </ul>

Upvotes: 0

Chandra Shekhar
Chandra Shekhar

Reputation: 3749

use this

CSS

ul
{
display:table;
width:100%;
}

li
{
display:table-cell;
}

use seperate media query to handle in the mobile view id needed.

Hope this helps :D

Upvotes: 0

Related Questions