简体   繁体   English

将 CSS 应用于第一个子元素,将 CSS 应用于元素内部的最后一个子元素,但如果只有子元素则不适用

[英]Apply CSS to first child and CSS to last child inside element but not if only child

I'm looking for an elegant SASS solution to apply a style to the first child and a different style to the last one inside an element, but then no style if it's the only child.我正在寻找一个优雅的 SASS 解决方案,将样式应用于第一个子元素,并将不同的样式应用于元素内的最后一个子元素,但如果它是唯一的子元素,则没有样式。

How could I accomplish that?我怎么能做到这一点?

An example would be:一个例子是:

  • If the element is the first child in a div , give it a margin-right property of 5px如果元素是div中的第一个子元素,则为其赋予5pxmargin-right属性
  • If the element is the last child in a div , give it a margin-left property of `5px如果元素是div中的最后一个子元素,则为其赋予 `5px 的margin-left属性
  • If the element is an only child in a div , let margin-right and margin-left be 0 .如果元素是div中的唯一子元素,则让margin-rightmargin-left0

Imagine I had the following:想象一下,我有以下内容:

<div>
  <i>Item 1</i>
  <span>Item 2</span>
  <i>Item 3</i>
</div>
  • I'd expect Item 1 to have a margin-right property of 5px , margin-left should be 0 .我希望Item 1margin-right属性为5pxmargin-left应该是0
  • I'd expect Item 2 to have no styles applied to it.我希望Item 2没有应用 styles。
  • I'd expect Item 3 to have a margin-left property of 5px , margin-right should be 0 .我希望Item 3margin-left属性为5pxmargin-right应该是0

If I had this example:如果我有这个例子:

<div>
  <span>Item</span>
</div>
  • I'd expect Item to have no styles applied to it我希望Item没有应用 styles

I've tried something like this:我试过这样的事情:

div {
  i {
    &:first-child {
      margin-right: 5px;
    }
    &:last-child {
      margin-left: 5px;
    }
  }
}

But this doesn't work if I have the case:但如果我有这种情况,这不起作用:

<div>
  <i>Item 1</i>
  <span>Item 2</span>
</div>

Because Item 1 has both margin-right and margin-left properties set to 5px when I actually want margin-right: 5px; margin-left: 0;因为当我真正想要margin-right: 5px; margin-left: 0;时, Item 1margin-rightmargin-left属性都设置为5px margin-right: 5px; margin-left: 0; . .

Any ideas on how to solve this?关于如何解决这个问题的任何想法? I'm a little rusty on my CSS-Selectors.我对我的 CSS 选择器有点生疏了。

A slight modification to your SASS rule could give your the result you want.对您的 SASS 规则稍作修改可能会给您想要的结果。 Try the following SASS rule.尝试以下 SASS 规则。

div {
  i {
    &:first-of-type {
      margin-right: 5px;
    }
    &:last-child {
      margin-left: 5px;
    }
  }
}

Just add a condition when the node it's the only child当节点是唯一的孩子时,只需添加一个条件

div {
  > * {
    &:first-child {
      margin-right: 5px;
    }
    &:last-child {
      margin-left: 5px;
    }
    &:only-child {
      margin: 0;
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM