0

I have the following html snippet

<body>
    <p>
        <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span><br />
    </p><p>
        <span>morbi id vestibulum lectus. maecenas facilisis orci vitae</span><br />
        <span>urna pulvinar cursus. etiam id laoreet metus. cras vitae</span><br />
        <span>elit ipsum. donec a sagittis nisi. sed nec nisi nibh,</span><br />
        <span>fringilla fermentum quam. vestibulum lorem felis, gravida</span><br />
        <span>et faucibus ac, ultrices nec lectus.</span>
    </p>
</body>

My css is the following

span:nth-of-type(3n+1) {
    color:red
    }
span:nth-of-type(3n+2) {
    color:green
    }
span:nth-of-type(3n+3) {
    color:blue
    }

I would like the second span ("morbi id...) to be colored in green and all the rest of span elements to follow reg-green-blue sequence. However, since span is inside the p element, it is colored in red, as nth-of-type takes into account order in relation to parent element. How can I accomplish this in css?

3
  • 2
    There's no way to link all those span tags, as they are not sibilings.... There are no such thing as "cousin" selector on css... Commented Sep 9, 2014 at 18:48
  • p:nth-child(2) span:first-child{color:green} Commented Sep 9, 2014 at 18:50
  • actually, spans have ids in this format id="sp-1", id="sp-2" etc. Would it be possible to do it in css using substring matching? Commented Sep 9, 2014 at 20:43

1 Answer 1

2

That is not possible. Since both the :nth-child and :nth-of-type or other variations similar to these 2 are related directly to their parents, you can't skip their immediate parent to search for the next match. The name itself "child" refers to the fact that they work only on immediate siblings.

You could achieve the effect using JQuery like $("body span:eq(0), body span:eq(3)").css("color","red"); or better, if your content is generated through PHP or something, mark those elements with a particular class using a count variable, and then define the color inside those class names in CSS.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.