CSS 使用 Sass 仅从元素中选择直接子元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30290820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 11:12:14  来源:igfitidea点击:

Select only direct children from element with Sass

csssass

提问by SuperDJ

Lets say I have the following html:

假设我有以下 html:

<header class="header">
    <div class="title">
        <h1>Home</h1>
    </div>

    <div class="logo">
        <img src="#" alt="Logo">
    </div>

    <div class="account">
        <div class="options">
        </div>

        <div class="search">
        </div>
    </div>
</header>

And I have the following SCSS:

我有以下 SCSS:

header {
    height: 4.1rem;

    div {
        width: 33%;
        float: left;
        height: 4.1rem;
        line-height: 4.1rem;
        color: #fff;

        &.title {
            h1 {
                font-weight: normal;
                font-size: 3rem;
                padding: 0;
                margin: 0;
            }
        }

        &.logo {
            text-align: center;
        }

        &.account {
        }
    }
}

Now the problem that I have is that divs optionsand searchare 33% percent of accountwhich is logic as I have div {width: 33%}. I know I can select direct child elements with:

现在我遇到的问题是 divoptionssearch33%account是逻辑,因为我有div {width: 33%}。我知道我可以选择直接子元素:

header {
  > div {
  }
}

But this doesn't help even if I put the >infront of all other classes. I also know I can say that the width should be 0 or what ever again in .accountbut I would like to prevent this.

但是,即使我把>所有其他类放在前面,这也无济于事。我也知道我可以说宽度应该是 0 或什么,.account但我想防止这种情况。

回答by Drops

Try this:

尝试这个:

    ...
    & > div {width: 33%;}

    div {
      float: left;
      height: 4.1rem;
      line-height: 4.1rem;
      color: #fff;
      ...

Take out div width and apply it only on direct children. Leave rest as is. Here is quick fiddle(remove .optionand .searchstyles later, its only for visualisation).

取出 div 宽度并将其仅应用于直接子级。保持原样休息。这是快速小提琴(稍后删除.option.search样式,仅用于可视化)。

Please edit your question and better explain what exactly you want to achieve.

请编辑您的问题并更好地解释您想要实现的目标。

回答by ryanpcmcquen

I am not certain I understand you. But I think you want a combination of direct children and child pseudo selectors, in pure CSS:

我不确定我理解你。但我认为您想要在纯 CSS 中组合直接子选择器和子伪选择器:

header > div:first-child {
}

Or, for the second div:

或者,对于第二个 div:

header > div:nth-child(2) {
}

You could also use the notselector:

您还可以使用not选择器:

header > div:not(.account) {
}

to exclude any unwanted div's.

排除任何不需要的 div。

回答by DINA TAKLIT

Use the &with >inside the parent element. Example:

在父元素内使用&with >。例子:

  .services{
            & > div {
                    margin-bottom: 25px;
            }
        }