有条件地应用 CSS

Conditionally apply a CSS

我定义了一个需要应用的样式只有如果有图标,如果没有则不需要。

带图标的html结构如下:

<li class="g-menu-item g-menu-item-226 g-menu-item-type-component g-standard">
  <a class="g-menu-item-container" href="/en/services/visas">
    <i class="fa fa-id-badge"></i>
    <span class="g-menu-item-content">
      <span class="g-menu-item-title">Visas</span>
    </span>
  </a>
</li>

没有图标的结构如下:

<li class="g-menu-item g-menu-item-232 g-menu-item-type-component g-standard">
  <a class="g-menu-item-container" href="/en/destinations/australia/adelaide">
    <span class="g-menu-item-content">
      <span class="g-menu-item-title">Adelaide</span>
    </span>
  </a>
</li>

我在带有图标的项目上运行良好的 SCSS。它将 class g-menu-item-title 的跨度向右移动 1.25rem,向上移动 1rem:

.aside-nav {
  .g-menu-item-container {
    .g-menu-item-content {
      margin-left: 1.25rem !important;
      margin-top: -1rem !important;
    }
  }
}

但是,当没有图标时,它会使侧边栏中的菜单项相互挤压。

如何更改此 SCSS,使其仅适用于旁边有图标的菜单项,而不适用于没有图标的菜单项。

您可以使用 Adjacent sibling selector,

它可以让您定位与另一个元素相邻的元素:

i + .g-menu-item-content {
   margin-left: 1.25rem !important;
   margin-top: -1rem !important;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<ul>
<li class="g-menu-item g-menu-item-232 g-menu-item-type-component g-standard">
  <a class="g-menu-item-container" href="/en/destinations/australia/adelaide">
    <span class="g-menu-item-content">
      <span class="g-menu-item-title">Adelaide</span>
    </span>
  </a>
</li>

<li class="g-menu-item g-menu-item-226 g-menu-item-type-component g-standard">
  <a class="g-menu-item-container" href="/en/services/visas">
    <i class="fa fa-id-badge"></i>
    <span class="g-menu-item-content">
      <span class="g-menu-item-title">Visas</span>
    </span>
  </a>
</li>
</ul>