-1

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.

slayer
  • 393
  • 1
  • 5
  • 19

2 Answers2

9

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>

Update based on a comment

If I understood correct .xyz:not(:last-child) target all "xyz" but the last

.parent {
  margin-top: 10px;
}
.parent .xyz {
  background: #ddd;
  margin: 1px;
}
.parent .xyz:not(:last-child) {
  display: none
}
<div class="parent">
    <div class="xyz">A 1</div>
</div>

<div class="parent">
    <div class="xyz">B 1</div>
    <div class="xyz">B 2</div>
</div>

<div class="parent">
    <div class="xyz">C 1</div>
    <div class="xyz">C 2</div>
    <div class="xyz">C 3</div>
</div>
Asons
  • 84,923
  • 12
  • 110
  • 165
  • It worked. Thanks a lot !!! – slayer Jun 12 '16 at 20:23
  • One more problem I'm facing...extension to this problem: I want to hide div "xyz" for all the child except last child. It should be dynamic i.e when first child comes up then xyz should be shown and when second one comes up then xyz of first child should be hidden and should be shown for second child. – slayer Jun 12 '16 at 20:32
  • @slayer Added a 2:nd sample target all but last – Asons Jun 13 '16 at 03:47
3

You're almost there

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

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

The space is very important here. It means that the :nth-child is a descendant of the parent.

Paulie_D
  • 107,962
  • 13
  • 142
  • 161