【问题标题】:Style nested divs with no class name specified未指定类名的样式嵌套 div
【发布时间】:2018-09-14 06:34:42
【问题描述】:

我想更改嵌套 div 的样式,如下例所示:

<div class="box">  #1
  <div>            #2
    <div>          #3
     <div>         #4
       <div></div> #5
       <div></div> #6
       <div></div> #7 **How to style this div when class name is not present?**
     </div>
    </div>
  </div>
</div>

我能够以这种方式访问​​ div #4:

.box div div div {}

但是访问 div #5 #6 #7 的方法是什么?

【问题讨论】:

  • 坦率地说,你真的需要开始使用类。
  • j08691 如果您知道请展示如何访问 #7,谢谢
  • 有很多方法可以做到这一点,但您将制造维护的噩梦。查看nth-of-type() 或另一种类型的选择器以获取一个选项。 (但请考虑这是否是最好的方法)
  • 如果此答案或任何答案解决了您的问题,请考虑通过单击复选标记并投票来接受它。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做:)

标签: css sass css-selectors


【解决方案1】:

要访问#7,您有两个或三个选项全部,其中使用直接后代选择器&gt; 将上下文限制为#4 div 的子项。

.box div div div > div:last-of-type{}
/* assumes there are no additional divs after #7 */

.box div div div> div:last-child {} 
/* assumes that the div is, in fact, the last child

甚至

.box div div div> div:nth-child(3) {}
/* assumes that the 3rd child is a div */

【讨论】:

    【解决方案2】:

    使用纯 CSS,您可以使用伪类 :last-child

    div.box > div > div > div > div:last-child {
      color:red;
    }
    <div class="box">  
      <div>            
        <div>          
         <div>         
           <div>5</div> 
           <div>6</div> 
           <div>7</div> 
         </div>
        </div>
      </div>
    </div>

    【讨论】:

      【解决方案3】:

      如果最后三个 div 元素真的没有内容,那么有一个捷径:

      .box div:empty:after { content: 'I am empty'; } /* all of them */

      .box div:empty:nth-child(1):after { content: 'Child 1'; } /* specific */

      【讨论】:

        【解决方案4】:

        您可以通过以下 css 行简单地实现此目的

        .box div:nth-child(3) {
          border: 1px solid red;
        }
        <div class="box">  
          <div>   
          1
            <div>  
              2
             <div>    
               3
               <div>&nbsp;&nbsp;&nbsp;4</div> 
               <div>&nbsp;&nbsp;&nbsp;5</div> 
               <div>&nbsp;&nbsp;&nbsp;7</div>
             </div>
             
            </div>
            
          </div>
          
        </div>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-06-17
          • 1970-01-01
          • 1970-01-01
          • 2017-08-15
          • 1970-01-01
          • 2020-03-14
          • 1970-01-01
          相关资源
          最近更新 更多