gpt4 book ai didi

Special property only when my element is first child of a container(仅当我的元素是容器的第一个子级时才有特殊属性)

转载 作者:bug小助手 更新时间:2023-10-26 21:30:06 26 4
gpt4 key购买 nike



I have an element that has its top and bottom margins set. It can also change position through a setting within its container. So it can be either the first child, or the last child of its container. But when it is the first child, I want its top margin to be 0.

我有一个元素,它设置了上边距和下边距。它还可以通过其容器内的设置来改变位置。因此,它可以是其容器的第一个子级,也可以是最后一个子级。但当它是第一个子级时,我希望它的上边距为0。


The problem is that none of the CSS combinators selects the first child. I can use the first-child pseudo class, but I don't want any first child to have its top margin set to 0. Only this particular one. So how can I achieve this?

问题是,没有一个css组合子选择第一个子级。我可以使用第一个孩子的伪类,但我不希望任何第一个孩子的上边距设置为0。只有这件特别的。那么,我如何才能做到这一点呢?


更多回答
优秀答案推荐

You can still use the :first-child pseudo-class selector but give that particular element a class that identifies it differently and only apply the style when it's the :first-child. This is when the element in question is the first child:

您仍然可以使用:first-Child伪类选择器,但为该特定元素提供一个以不同方式标识它的类,并且仅当它是:first-Child时才应用该样式。这是当有问题的元素是第一个子元素时:




p {
font-weight: bold;
}

li{
margin-top: 5px;
margin-bottom: 5px;

}

li.special:first-child {
margin-top: 50px;
}

<p>NBA players with most championships:</p>
<ul>
<li class="special">Bill Russell</li>
<li>Sam Jones</li>
<li>Tom Heinsohn</li>
<li>K. C. Jones</li>
<li>Satch Sanders</li>
<li>John Havlicek</li>
<li>Jim Loscutoff</li>
<li>Frank Ramsey</li>
<li>Robert Horry</li>
</ul>




This is the element when it's not the first child:

这是不是第一个子元素时的元素:




p {
font-weight: bold;
}

li{
margin-top: 5px;
margin-bottom: 5px;

}

li.special:first-child {
margin-top: 50px;
}

<p>NBA players with most championships:</p>
<ul>
<li>Sam Jones</li>
<li class="special">Bill Russell</li>
<li>Tom Heinsohn</li>
<li>K. C. Jones</li>
<li>Satch Sanders</li>
<li>John Havlicek</li>
<li>Jim Loscutoff</li>
<li>Frank Ramsey</li>
<li>Robert Horry</li>
</ul>




As you can see the margin-top: 50px is only applied when it's the first-child.

如你所见,页边距-顶部:50px只适用于第一个孩子。


更多回答

I had the impression that :first-child refers to the first child of an element. Not to the element itself when it is the first child of another element. Thanks a lot for the clarification and the answer also.

我的印象是:第一个孩子指的是一个元素的第一个孩子。而不是元素本身,因为它是另一个元素的第一个子级。非常感谢你的澄清和回答。

You're welcome. As long as the element is among a group of sibling elements then you can select it with :first-child. Good luck with your project.

不客气只要元素是在一组兄弟元素中,那么你就可以用:first-child来选择它。祝你项目顺利

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com