slayer slayer - 5 months ago 8
CSS Question

CSS for first and last child

I need to apply CSS to first and last child.

Here is my code:

<div class="parent">
<div class="A B"><div class="xyz"></div></div>
<div class="A B"><div class="xyz"></div></div>
<div class="A B"><div class="xyz"></div></div>
</div>

.parent {
display: inline-block;
width: 100%;
}

.A {
display: inline-block;
max-width: 75%;
position: relative;
clear: both;
}

.B {
float: left;
padding: 10px;
}


I was trying to do as following:

.parent:first-child {
margin-top: 15px;
}

.parent:last-child {
margin-bottom: 2px;
}


So that first child top margin becomes 15px and gap between all the child become 4px;

But it's not working. Kindly help me to solve this problem.

Answer

Do like this, where you use the pseudo :first-child/:last-child on the group of elements you want to target, not their parent.

You can use the type, div:first-child, which I used in my sample, or a class like .A:first-child

Side note:

  • There was a syntax error in the markup, a missing > on parent div, which also can cause the CSS to fail (now fixed with your edit)
  • Missing space between .parent and the :first-child/:last-child rules

.parent div:first-child {
    margin-top: 15px;
  background: blue;
}

.parent div:last-child {
    margin-bottom: 2px;
  background: red;
}
<div class="parent">
    <div class="A B">...</div>
    <div class="A B">...</div>
    <div class="A B">...</div>
</div>