Home > Software design >  I can't select my second paragraph inside my parent class
I can't select my second paragraph inside my parent class

Time:10-05

I have the following html

  <div class="parentt">
        <p>p 1</p>
        <p>p 2</p>
        <p>p 3</p>
    </div>

so if i want to style the second p inside my parentt class i will do

.parentt > p:nth-child(2) {
    border: 1px solid red;
}

but when my html is mixed

<div class="parentt">
        <p>p 1</p>
        <h2>sdsd</h2>
        <p>p 2</p>
        <p>p 3</p>
    </div>

and i put inside h2 tag, my css is not working any more because now nth-child 2 is not paragraph but it is h2.

How can i dynamically first select all p inside and after that to select the second p inside?

Because sometimes the second p inside the parrent can appear on nth-child number 8 for example. I can't change every time my css.

CodePudding user response:

Use nth-of-type

.parentt > p:nth-of-type(2) {
    border: 1px solid red;
}

https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-of-type

CodePudding user response:

In such cases you could use nth-of-type instead of nth-child

.parentt > p:nth-of-type(2) {
    border: 1px solid red;
}
<div class="parentt">
        <p>p 1</p>
        <h2>sdsd</h2>
        <p>p 2</p>
        <p>p 3</p>
    </div>

CodePudding user response:

You can use :nth-of-type() pseudo selector. You can read more here

.parentt p:nth-of-type(2) {
  border:1px solid red;
}
<div class="parentt">
  <p>p 1</p>
  <h2>sdsd</h2>
  <p>p 2</p>
  <p>p 3</p>
</div>

CodePudding user response:

You can specify an id to that p tag like

.parentt #child {
  background: red;
}
<body>

<div class= 'parentt'>
<p>The first paragraph.</p>
<h2>Hello World </h2>
<h2>Hello World </h2>
<h2>Hello World </h2>
<p id='child'>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
</div>
</body>

  • Related