css和/或SASS +(同级)选择器向上\[重复\]

sass CSS

Mandy小小西门

2020-03-19

In CSS there is no way to select a sibling with plus if the sibling is above in the output, a preceding element in the html.

For example

<div class="first">
<div class="second">

.second + .first { style applied to div.first}

Is there anyway to do this in SASS/SCSS?

第2380篇《css和/或SASS +(同级)选择器向上\[重复\]》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
蛋蛋Davaid猴子 2020.03.19

可能会或可能不适合您的需求,但是您可以在Sass / CSS中使用常规的同级选择器。这将选择同一节点级别上的所有元素(在此之前未明确指定,但仍很方便):

.second {
   .first ~ & {
       /* styles to be applied to .second if a .first exists at the same node level */   
   }
}
Tom米亚老丝 2020.03.19

SASS支持所有CSS3选择器。同胞+是其中之一。但这并没有带来一些额外的功能。这意味着你可以做

first {
  + second { 
     font-size: smaller;
  }
}

但是你不能用它影响父母...

ps:这似乎是CSS4的功能:)

LEYPro前端 2020.03.19

我最终使用了Jquery。完成工作:)(对不起,我走了另一条路线时,我不再有示例代码,但是它很简单,就像“如果孩子有课,然后给它添加课”。:)

ALEYHarry 2020.03.19

我知道这种感觉,真是烦人。我发现了一种快速的方法。

的HTML

<div class="mainmenu">
  <div class="subnav">
    <ul>
      <li>Whatever</li>
    </ul>
  </div>
</div>

SCSS

CSS指向朝至的第一个孩子div "mainmenu"> class "subnav"

 .mainmenu{
      & > .subnav{
         // Child Selector SCSS HERE
      }
  }

@thgaskell,您证明我错了:)我的代码工作正常,我丢失了6KB的缩小代码!我已经更新了代码,并告知了以下评论。

神无Tom 2020.03.19
div { & + & { margin-left: 15px; background: firebrick;}}

尝试它的工作。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android