-4

i have the following HTML

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

so if i want to style all paragraphs inside i will do

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

but if i have nested paragraphs for example

<div class="parentt">
        <h2>sdsd</h2>
        <p>p 1</p>
        <p>p 2</p>
        <p>p 3</p>
       <div class="my-div-with-nested-p">
          <p>nested p 1</p>
         <div> <p>nested p 2</p></div>
       </div>
  </div>

then my css code does not work.How can i style the nested paragraphs - nested p 1 and nested p 2 automatically throught the parent like in the first case ?

peckoski
  • 105
  • 6
  • Which element you want to select ? – Viira Oct 07 '21 at 10:18
  • Are you wanting to style the nested `p` as well as the normal `p` tags? You can just remove your `:nth-of-type` if this is the case and it will style all `p` tags inside of `parentt` – MattHamer5 Oct 07 '21 at 10:19
  • 3
    ```.parentt p {}``` will give you all the `p` tags in this ```div```. – prettyInPink Oct 07 '21 at 10:20
  • did you try like this? `p { /* css codes... */ }` in this case you don't need any nested selectors, apparently you didn't search before: `https://stackoverflow.com/questions/4910077/select-all-child-elements-recursively-in-css` – Mohammad Esmaeilzadeh Oct 07 '21 at 10:22

1 Answers1

-1

You can use Descendant selectors to select a nested child.

.parentt * p, .parentt > p{
  color: red;
}
<div class="parentt">
        <h2>sdsd</h2>
        <p>p 1</p>
        <p>p 2</p>
        <p>p 3</p>
       <div class="my-div-with-nested-p">
          <p>nested p 1</p>
         <div> <p>nested p 2</p></div>
       </div>
</div>

Official Specification: 5.5 Descendant selectors

OR

You can directly apply properties to all <p> inside .parentt div.

.parentt p{
  color:red;
}
 <div class="parentt">
            <h2>sdsd</h2>
            <p>p 1</p>
            <p>p 2</p>
            <p>p 3</p>
           <div class="my-div-with-nested-p">
              <p>nested p 1</p>
             <div> <p>nested p 2</p></div>
           </div>
    </div>
mr.Hritik
  • 577
  • 3
  • 19