1

I have problem with first-child selector. In code I have two div (this same class), img (in every) and p (in every). When i type in CSS .div-class:first-child {margin:10}, in the p a margin is added and only in first div.

First ask: why margin was not added to img (first element in div) Second ask: why margin is added only first div (second have this same class name)

<section class="section-offer">

    <div class="section-offer-single">
        <img src="images/pizza.png" alt="Pizza">
        <p>Some text</p>
    </div>

    <div class="section-offer-single">
        <img src="images/pizza.png" alt="Pizza">
        <p>Some text</p>
    </div>

</section>


.section-offer-single:first-child{
  margin: 0px 0px 130px;
}

2 Answers2

1

:first-child is a selector used to select an element that is a first child, not the first child of that element.

To get the first children of the .section-offer-single elements, use the selector:

.section-offer-single > :first-child

This also explains why only the first .section-offer-single had the styles applied to it -- this is because it is the (only) first child of its parent.

Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94
0

why margin was not added to img (first element in div)

The selector is .section-offer-single:first-child. While :first-child matches the <img>, .section-offer-single does not.

why margin is added only first div (second have this same class name)

The second <div> matches .section-offer-single but doesn't match :first-child.


A selector only matches if the whole selector matches. (Keeping in mind that , groups multiple selectors together on one rule-set).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335