Navbar link margin 类 在 Tailwind CSS 中似乎重复,有没有更好的方法?

Navbar link margin classes seem repetitive in Tailwind CSS, is there a better way?

必须为每个 LI 添加边距 类 在不是动态生成的菜单上看起来真的很重复。这感觉像使用 style="" 属性一样脏...

肯定有更好的方法吗?

小菜单没什么大不了的,但最终菜单会有很多级别的子菜单。

我想知道我是否应该在我的样式表中写一个规则来在我的菜单项上添加边距?

<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">

<nav class="p-2 bg-indigo-900 text-white">
    <ul class="flex flex-row">
        <li class="mr-1">
            <a href="#">Home</a>
        </li>
        <li class="ml-1 mr-1">
            <a href="#">About</a>
        </li>
        <li class="ml-1 mr-1">
            <a href="#">Services</a>
        </li>
        <li class="ml-1 mr-1">
            <a href="#">History</a>
        </li>
        <li class="ml-1">
            <a href="#">Contact</a>
        </li>
    </ul>
</nav>

我不熟悉 tailwind-css 但您可以使用 :last-child:first-child 选择器。

nav ul li {
  margin-left: 10px;
  margin-right: 10px;
}

nav ul li:first-child {
  margin-left: 0px;
}

nav ul li:last-child {
  margin-right: 0px;
}
<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">

<nav class="p-2 bg-indigo-900 text-white">
  <ul class="flex flex-row">
    <li class="">
      <a href="#">Home</a>
    </li>
    <li class="">
      <a href="#">About</a>
    </li>
    <li class="">
      <a href="#">Services</a>
    </li>
    <li class="">
      <a href="#">History</a>
    </li>
    <li class="">
      <a href="#">Contact</a>
    </li>
  </ul>
</nav>

我要将上面的答案标记为正确,因为我没有提供关于这是一个 Laravel 项目的上下文。我已经确定的是为我的导航创建一个部分,然后我将一组标签和 urls

传递给它
// snippet of layouts/app.blade.php
@include('layouts._nav', ['links' => [
    [ 'label' => 'Main feed', 'url' => '/posts' ],
    [ 'label' => 'Announcements', 'url' => '/announcements' ],
    [ 'label' => 'Who to follow', 'url' => '/who-to-follow' ],
    [ 'label' => 'Profile', 'url' => '/profiles' ]
]])
// layouts/_nav.blade.php
<nav class="p-2 bg-indigo-900 text-white">
    <ul class="flex flex-row">
        @foreach($links as $link)
            @php
                if($loop->iteration === 1)
                    $class = 'mr-1';
                elseif($loop->iteration === $loop->count)
                    $class = 'ml-1';
                else
                    $class = 'ml-1 mr-1';
            @endphp
            <li class="{{ $class }}">
                <a href="{{ $link['url'] }}">{{ $link['label'] }}</a>
            </li>
        @endforeach
    </ul>
</nav>

输出HTML:


<nav>
    <ul class="flex flex-row">
        <li class="mr-1">
            <a href="/posts">Main feed</a>
        </li>
        <li class="ml-1 mr-1">
            <a href="/announcements">Announcements</a>
        </li>
        <li class="ml-1 mr-1">
            <a href="/who-to-follow">Who to follow</a>
        </li>
        <li class="ml-1">
            <a href="/profiles">Profile</a>
        </li>
    </ul>
</nav>