html - CSS 选择器 :nth-child(even|odd) vs :nth-child(int)

标签 html css css-selectors

我在使用 CSS :nth-child 伪选择器时遇到以下问题,我很确定我漏掉了一些东西。

index.html

<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(不起作用)

.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(用于证明选择器概念)

.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 动态注入(inject)和移除元素。

更新/附加

不幸的是,我在上面的例子中打错了字。但不幸的是,这并没有解决实际情况——即使我看到了有效的 JS-Fiddles(因此我真的很困惑......)

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

Markup Sample

CSS:

.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; }

最佳答案

您没有在第二个 .selector 中关闭 div。工作正常:

fiddle

关于html - CSS 选择器 :nth-child(even|odd) vs :nth-child(int),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25504988/

相关文章:

javascript - 使用向下/向上滑动过渡动画 v-if (Vue.js 2)

html - 如何使用CSS为输入边框底部着色

javascript - TypeError : $ . 查找不是函数

CSS - 将相邻选择器与 nth-of-type 结合使用

javascript - 使用 JS 获取复选框值

html - 如何更改导航栏位置? CSS & HTML

html - 将图像插入另一个 div 后 ul 菜单下降

html - 在兄弟悬停时设置 span 标签的 CSS

css - 使用 css 选择器禁用与复选框关联的标签

css - 在带有大背景图像的 chrome 中滚动不连贯