0

I've got an unordered list with a few list items. I'm trying to decrease the spacing between the list items, but they won't get any closer than they already are. Anyone have any suggestions?

Here is the relevant code:

ul.mainNav {
  float: right;
  padding-right: 185px;
}

li.mainNavItem {
  color: blueviolet;
  text-align: center;
  list-style: none;
  display: inline-block;
  background-color: #000000;
  width: 130px;
  line-height: 50px;
}
<ul class="mainNav">
  <li class="mainNavItem">hi</li>
  <li class="mainNavItem">hello</li>
  <li class="mainNavItem">welcome</li>
  <li class="mainNavItem">hallo</li>
</ul>

I've tried playing with the margins, but even at .01px, the list items wouldn't get closer together. I do want some space between them, albeit very little, so creating a bar wouldn't solve my problem either.

Thanks in advance for any suggestions!

tacoshy
  • 10,642
  • 5
  • 17
  • 34
Yikes
  • 87
  • 1
  • 11
  • 1
    First of: stop using `float` unless you really know what you're doing. Explore the magic of CSS **Flex**. Also, why don't you provide an image of the desired (or explain better) ? – Roko C. Buljan Oct 22 '21 at 21:58

2 Answers2

1

You can use flexbox here

1) If you gonna add display: flex; on ul, then there won't be any space between its children.
2) You can add gap on the ul for space between 2 li.

gap: 1px;            // space between two li

ul.mainNav {
  display: flex;
  justify-content: center;
  gap: 1px;
}

li.mainNavItem {
  color: blueviolet;
  text-align: center;
  list-style: none;
  display: inline-block;
  background-color: #000000;
  width: 130px;
  line-height: 50px;
}
<ul class="mainNav">
  <li class="mainNavItem">hi</li>
  <li class="mainNavItem">hello</li>
  <li class="mainNavItem">welcome</li>
  <li class="mainNavItem">hallo</li>
</ul>
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • `li + li {margin-left: 1px; }` can you explain why the last li should have a 1px left margin and the first one not as well a 1px right margin? `gap: 1px;` is a far better solution. – Roko C. Buljan Oct 22 '21 at 22:03
  • @RokoC.Buljan `li + li` is not the right tool here. Thanks – DecPK Oct 22 '21 at 22:07
-3

One option might be to use negative margin? It seems to work with your example.

margin-left: -10px;

 ul.mainNav{
    float: right;
    padding-right: 185px;
}

li.mainNavItem{
    color: blueviolet;
    text-align: center;
    list-style: none;
    display: inline-block;
    background-color: #000000;
    width: 130px;
    line-height: 50px;
    margin-left: -10px;
}
<ul class="mainNav">
    <li class="mainNavItem">hi</li>
    <li class="mainNavItem">hello</li>
    <li class="mainNavItem">welcome</li>
    <li class="mainNavItem">hallo</li>
</ul>
Joshua
  • 184
  • 1
  • 11