volume one volume one - 4 months ago 10
CSS Question

How to remove margin on horizontal list line break?

I have a top navigation bar which I want to be always visible even when the screen is only 320px wide. Here is what I have done:

<nav>
<ul>
<li>Products</li>
<li>Services</li>
<li>Videos</li>
<li>News</li>
<li>Contact</li>
</ul>
</nav>


I display the list horizontally using this CSS:

nav li { float: left; }
nav li + li { margin-left: 30px; }


I end up with this:

Products Services Videos News Contact


This is fine until the screen becomes small and the final two list items get pushed down to the next row like this:

Products Services Videos
News Contact


I need to remove the left margin of the first item that is on a new row like this:

Products Services Videos
News Contact


How could this be achieved? I don't mind changing my HTML and CSS completely to achieve it - as long as it can be done!

Answer

You could simply apply a right margin instead of left margin. That way when items are broken into a new line, there will not be a space before them:

nav li { float: left; margin-right: 30px; }
<nav>
  <ul>
  <li>Products</li>
  <li>Services</li>
  <li>Videos</li>
  <li>News</li>
  <li>Contact</li>
 </ul>
</nav>

css menu margin

jsfiddle: https://jsfiddle.net/azizn/v1f9hL04/

Comments