Special property only when my element is first child of a container

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.

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?

>Solution :

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:

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.

Leave a Reply