I am trying to target first image in every post. The example post where I am trying to perform this is here.
So I tried to use first-of-type
like this
.single-post .entry-content img.aligncenter:first-of-type {
width: 80% !important;
float: left;
}
And also tried to replace first-of-type
with first-child
and I get the same result and that is every image is selected instead of first one. I think that this should only select the first image with occurrence of .aligncenter
class.
1 Answer
Firstly i would say this is off-topic here as it purely relates to css/js, but let me try to give some pointers.
Here you markup is :
<article>
<header></header>
<div>
....
<p><img class="align-center" src="https://wordpress.stackexchange.com/questions/225091/path/to/img1"></p>
....
<p><img class="align-center" src="path/to/img2"></p>
....
</div>
</article>
first-of-type means selecting the first child of the selector parent.
In the above markup , the targeted selector is image with class align-center and the selector parent is p. So selecting the first child of the selector parent matches both images. That’s why both images are being styled.
first-child means select an element if it is an image with class align-center and and is the first child of a parent selector. So it matches both images.
I would recommend using JavaScript selectors here.
document.querySelector(".single-post .entry-content img.aligncenter")
returns first element in the result.
If you are using jQuery use :first
filter.
References:
first-of-type
first-child
SO