css nth-child以其他方式找到元素

时间:2015-08-07 16:54:02

标签: html css css-selectors

有没有办法以第三个.slide元素为目标,使用这样的css代码:

HTML

<div id="slides">

    <section>
        <div class='slide'></div>   this should be 1
        <div class='slide'></div>   this should be 2
        <div class='slide'></div>   this should be 3
    </section>

    <section>
        <div class='slide'></div>   this should be 4
    </section>

    <section>
        <div class='slide'></div>   this should be 5     I target this one
        <div class='slide'></div>   this should be 6
        <div class='slide'></div>   this should be 7
    </section>

</div>

CSS

.slide:nth-of-type(5) {
    background:red;
}

我认为这样的事情会奏效,但事实并非如此。

我基本上想要使用相应的数字访问每个元素,因此在css

中使用7进行第7次访问

如果需要,我可以打开jquery解决方案

4 个答案:

答案 0 :(得分:1)

它不会那样工作,它只会针对该部分中的.slide:

&#13;
&#13;
section:nth-of-type(3) .slide:first-of-type {
    background:red;
}
&#13;
<div id="slides">

    <section>
        <div class='slide'></div>   this should be 1
        <div class='slide'></div>   this should be 2
        <div class='slide'></div>   this should be 3
    </section>

    <section>
        <div class='slide'></div>   this should be 4
    </section>

    <section>
        <div class='slide'>this should be 5      I target this one </div>
        <div class='slide'>this should be 6</div>   
        <div class='slide'>this should be 7</div>   
    </section>

</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

Jquery解决方案

$('#slides .slide').eq(4).css("color", "red");

&#13;
&#13;
$('#slides .slide').eq(4).css("color", "red");
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="slides">

  <section>
    <div class='slide'>this should be 1</div>
    <div class='slide'>this should be 2</div>
    <div class='slide'>this should be 3</div>
  </section>

  <section>
    <div class='slide'>this should be 4</div>
  </section>

  <section>
    <div class='slide'>this should be 5 I target this one</div>
    <div class='slide'>this should be 6</div>
    <div class='slide'>this should be 7</div>
  </section>

</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

这里你去http://jsfiddle.net/DIRTY_SMITH/ns3u7uf5/12/

<强> CSS

section:nth-child(3) > .slide:nth-child(1) {
    color:red;
}

<强> HTML

<div id="slides">

    <section>
        <div class='slide'>  this should be 1</div>
        <div class='slide'>  this should be 2</div>
        <div class='slide'>  this should be 3</div>
    </section>

    <section>
        <div class='slide'>  this should be 4</div>
    </section>

    <section>
        <div class='slide'>   this should be 5     I target this one</div>
        <div class='slide'>  this should be 6</div>
        <div class='slide'>   this should be 7</div>
    </section>

</div>

答案 3 :(得分:-1)

您正在尝试使用专为类中的类型设计的选择器。因此nth-of-type名称。可悲的是,据我所知,没有办法将这个选择器用于类。

您可能希望使用编程逻辑为所需的每个间隔添加新类。然后你可以使用这样的东西:

section.highlight {
    color:red;
}

有人遇到了同样的情况:css3 nth of type restricted to class