问题描述:

I would like to change the background color in 2n element. I've tested it but the bg-color is still blue:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>nothing here</title>

</head>

<body>

<style type="text/css">

.btn{

height:50px;

width:100%;

background:blue;

margin-bottom:20px;

}

.btn:nth-child(2n){

background:yellow;

}

</style>

<div>

<div class="btn"></div>

</div>

<div>

<div class="btn"></div>

</div>

</body>

</html>

网友答案:

it should be more like :

 .btn{
        height:50px;
        width:100%;
        background:blue;
        margin-bottom:20px;
    }
    div:nth-child(2n) .btn{
        background:yellow;  
    }

Because, in each div , there's only one .btn

nth-child works with adjacent element, not nested unfortunately :)

网友答案:

.btn is inside a div.

.btn:nth-child(2n) will work if your HTML structure is as follows:

<div>
    <div class="btn"></div>
    <div class="btn"></div>
</div>

For your HTML structure, it should be

div:nth-child(2n) .btn {
    background:yellow;
}

DEMO here.

相关阅读:
Top