Harsh Gupta
Harsh Gupta

Reputation: 173

Get first child of p inside span element

I need to get the first child of p elements (being created dynamically through JS and have same id). Basically I want to add a margin-top to the first p child element.

<div class="col-xs-12 col-sm-10 col-sm-offset-1 col-md-8 col-md-offset-2" id="exmkp" style="display:none">
      <span id="heading"></span>
        <p>......</p>
        <p>......</p>

Upvotes: 2

Views: 1665

Answers (3)

Paracetamol
Paracetamol

Reputation: 352

You could create a rule for any child element like this

div#exmkp > p {
    margin-top : 10px;
}

and then revoke it for any element that's coming after another

div#exmkp > p + p {
    margin-top : 0;
}

this does only work for groups of paragraphs though (as in your example) – not, if they are interrupted by other elements. (Working Example)

Upvotes: 0

GreyRoofPigeon
GreyRoofPigeon

Reputation: 18133

Use the :first-of-type pseudo class for that. It will always select the first paragraph inside div#exmkp, even when the paragraph isn't the first child.

#exmkp p:first-of-type {
  background: yellow;
}
<div class="col-xs-12 col-sm-10 col-sm-offset-1 col-md-8 col-md-offset-2" id="exmkp">
  <span id="heading">Heading</span>
  <p>......</p>
  <p>......</p>
</div>

Additional info
If you want to select the first paragraph, but only when it also is the first child inside the div, you can use #exmkp p:first-child.

Upvotes: 7

Vineeta Mehta
Vineeta Mehta

Reputation: 458

nth-of-type pseudo selector can be used to target specific elements in a div try this :

div#exmkp p:nth-of-type(1) {
       margin-top : 10px;
    }

Upvotes: 3

Related Questions