首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >css选择器:n-子(偶数,奇数)与:n-子(Int)

css选择器:n-子(偶数,奇数)与:n-子(Int)
EN

Stack Overflow用户
提问于 2014-08-26 11:41:03
回答 4查看 338关注 0票数 2

我有下面的CSS :nth-child伪选择器的问题,我很肯定我遗漏了一些东西。

index.html

代码语言:javascript
复制
<html>
<head>...</head>

    <body>

        <div class='selector'>first</div>
        <div class='selector'>second</div>
        <div class='selector'>third</div>
        <div class='selector'>fourth</div>
        <div class='selector'>fifth</div>

    </body>

</html>

style_does_not_work.css (不工作)

代码语言:javascript
复制
.selector { background-color: #ffffff; }
.selector:nth-child(1) { background-color: #f00000; }
.selector:nth-child(2) { background-color: #ff0000; }
.selector:nth-child(3) { background-color: #fff000; }
.selector:nth-child(4) { background-color: #ffff00; }
.selector:nth-child(5) { background-color: #fffff0; }

style_that_works.css (用于证明选择器概念)

代码语言:javascript
复制
.selector { background-color: #ffffff; }
.selector:nth-child(even) { background-color: #f00000; }
.selector:nth-child(odd) { background-color: #ff0000; }

我有点搞不懂为什么:nth-child(2)不工作,但:nth-child(even)工作。有什么不同吗?我错过了什么?

我的目标是给固定位置的元素一个从顶部的动态偏移,而元素被注入和动态删除javascript。

更新/附加

不幸的是,我在上面的例子中做了一个错误。但不幸的是,这并没有解决真正的问题--甚至我看到了工作中的JS(我为此感到非常困惑.)

此外,我还发布了一些当前问题的屏幕:

CSS:

代码语言:javascript
复制
.notification-area {
    position: fixed;
    z-index: 999;
    width: 500px;
    height: 100%;
    overflow: hidden;
}

.notification-area.top-right {
    top: 25px;
    right: 25px;
    left: auto;

    -webkit-transition: margin 0.4s, top 0.4s, left 0.4s, right 0.4s, bottom 0.4s;
    -moz-transition: margin 0.4s, top 0.4s, left 0.4s, right 0.4s, bottom 0.4s;
    -ms-transition: margin 0.4s, top 0.4s, left 0.4s, right 0.4s, bottom 0.4s;
    -o-transition: margin 0.4s, top 0.4s, left 0.4s, right 0.4s, bottom 0.4s;
    transition: margin 0.4s, top 0.4s, left 0.4s, right 0.4s, bottom 0.4s;

}

/* these lines are completely ignored */

.notification-area:nth-child(2) { margin: 125px 0px 0px 0px; }
.notification-area:nth-child(3) { margin: 250px 0px 0px 0px; }
.notification-area:nth-child(4) { margin: 375px 0px 0px 0px; }
.notification-area:nth-child(5) { margin: 500px 0px 0px 0px; }


/* this line grabs instead - I don't want to use "even", but it shows me, that the selector :nth-child() should be fine... */
.notification-area:nth-child(even) { margin: 125px 0px 0px 0px; }
EN

回答 4

Stack Overflow用户

发布于 2014-08-26 11:47:17

您没有在第二个.selector中关闭.selector。工作良好:

fiddle

票数 7
EN

Stack Overflow用户

发布于 2014-08-26 11:47:52

你错过了第二频道的闭幕式。

票数 1
EN

Stack Overflow用户

发布于 2014-08-26 11:48:14

试试这个:nth-child(n+1)而不是:nth-child(2)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25504988

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档