[英]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:一个例子是:
div
, give it a margin-right
property of 5px
div
中的第一个子元素,则为其赋予5px
的margin-right
属性div
, give it a margin-left
property of `5pxdiv
中的最后一个子元素,则为其赋予 `5px 的margin-left
属性div
, let margin-right
and margin-left
be 0
.div
中的唯一子元素,则让margin-right
和margin-left
为0
。 Imagine I had the following:想象一下,我有以下内容:
<div>
<i>Item 1</i>
<span>Item 2</span>
<i>Item 3</i>
</div>
Item 1
to have a margin-right
property of 5px
, margin-left
should be 0
.Item 1
的margin-right
属性为5px
, margin-left
应该是0
。Item 2
to have no styles applied to it.Item 2
没有应用 styles。Item 3
to have a margin-left
property of 5px
, margin-right
should be 0
.Item 3
的margin-left
属性为5px
, margin-right
应该是0
。 If I had this example:如果我有这个例子:
<div>
<span>Item</span>
</div>
Item
to have no styles applied to itItem
没有应用 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 1
的margin-right
和margin-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.