Вопрос

I am new to CSS/HTML and have a question regarding nesting (one I think many others might encounter as they are new to CSS). I have the following code:

<article id="rightarticle">
     <h2 id="sightings">Cougar Sightings Increase <img src="cougar.jpg" alt="BEWARE"/></h2>  

The h2 element is not the only h2 element under the article subsection; however, it is the first. My goal is to target only the first h2 element to change its background.

Without using the #sightings reference - i.e. the id - how do I reference only the first h2 element of the article element in CSS? Accepting symantic conventions, that article is the largest element, I am assuming I could not use a first-child reference to isolate only the element above?

Это было полезно?

Решение

Use a > child selector and :first-of-type psuedo class selector.

Select by #rightarticle ID:

#rightarticle > h2:first-of-type {}

Select by <article> tag:

article > h2:first-of-type {}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top