Grab child element in css

Asked

Viewed 5,589 times

0

I have the following html structure:

<div class="box1">
 <p>texto</p>
 <p>texto</p>
 <p><img src="imagem1.jpg"></p>
 <p>texto</p>
</div>
<div class="box2">
 <p>texto</p>
 <p>texto</p>
 <p><img src="imagem1.jpg"></p>
 <p>texto</p>
</div>

How do I apply, for example, a padding in the img tag inside box2 via css?

Thank you

3 answers

2

From the title of the question, I believe the solution would be:

div > p > img {
    padding: 10px;
}

The operator > will fetch any direct child element among the related elements. This is, div > p search for all elements p which have a parent element div and p > img search for all elements img which have a parent element p.

Take an example:

div > p > img {
  padding: 10px;
  border: 1px solid black;
}
<div class="box1">
 <p>texto</p>
 <p>texto</p>
 <p><img src="http://via.placeholder.com/350x150"></p>
 <p>texto</p>
</div>
<div class="box2">
 <p>texto</p>
 <p>texto</p>
 <p><img src="http://via.placeholder.com/350x150"></p>
 <p>texto</p>
</div>

How >, + , ~ selectors work in CSS?

1

uses like this:

.box2 p img
{
   Código
}

1

.box2 img {
   padding: 5px;
}

As you only have an image inside the box2 vc can do as exemplified above (with inheritance).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.