Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading