最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using nth-child to make a chess pattern - Stack Overflow

programmeradmin7浏览0评论

I am breaking my head to achieve something quite relatively simple here.

I need to select every 3rd and 4th element on my page, how could I do that using css :nth-child()?

JS answers also wele.

Thanks a lot.

***EDIT

Apologies guys my question was badly written. I attached an example below of what I need.

This is the oute I need, /

        <li></li>
        <li class="highlight"></li>
        <li class="highlight"></li>
        <li></li>
        <li></li>
        etc

Without hardcoding the class names.

I am breaking my head to achieve something quite relatively simple here.

I need to select every 3rd and 4th element on my page, how could I do that using css :nth-child()?

JS answers also wele.

Thanks a lot.

***EDIT

Apologies guys my question was badly written. I attached an example below of what I need.

This is the oute I need, http://jsfiddle/8FXL6/

        <li></li>
        <li class="highlight"></li>
        <li class="highlight"></li>
        <li></li>
        <li></li>
        etc

Without hardcoding the class names.

Share Improve this question edited Nov 15, 2012 at 11:32 peduarte asked Nov 15, 2012 at 11:20 peduartepeduarte 1,6773 gold badges16 silver badges24 bronze badges 1
  • 4 Please add some example markup, and what you expect to be found. – Jamiec Commented Nov 15, 2012 at 11:22
Add a ment  | 

5 Answers 5

Reset to default 11
*:nth-child(3),*:nth-child(4){
}

Technically, this selects every element that is the 3rd or 4th child in its container. If you want to select every 3rd or 4th element (3,4,6,8 etc.), use:

*:nth-child(3n),*:nth-child(4n){
}

DEMO

From your edit, you need:

li:nth-child(4n-2),li:nth-child(4n-1){
}

DEMO

You can use ma to bine selectors using nth-child to get elements,

Live Demo

elements = $('div .className :nth-child(3), div .className :nth-child(4)');

How about using css only?

Every third element:

*:nth-child(3n+3) {color: red}

Every fourth element:

*:nth-child(4n+4) {color: blue}

Here's demo on jsfiddle: http://jsfiddle/dufsx/

This can be solved using CSS only

 *:nth-child(4n+2){background:blue;color: white;}
 *:nth-child(4n+3){background:blue;color: white;}

LIVE DEMO

you can use the solution below,

ul:nth-of-type(2n) li:nth-of-type(2n+1) {
background-color: black;
}
ul:nth-of-type(2n+1) li:nth-of-type(2n) {
background-color: black;
}
发布评论

评论列表(0)

  1. 暂无评论