zoukankan      html  css  js  c++  java
  • css 选择器之子元素

    /*html*/
    <div class="wrap">
        <span>1</span>
        <span>2</span>
        <span>3</span>
        <span>4</span>
    </div>
    
    /*css*/
    .wrap{
        display:table;
         200px;
    }
    .wrap span{
        display:table-cell;
        text-align:center;
    }
    

    nth-child(n)

    //选择父元素下的第二个子元素,且为span
    .wrap span:nth-child(2){
        color:red;
    }
    

    但是如果子元素是混乱的,比如:

    <div class="wrap">
        <span>1</span>
        <p>p</p>
        <span>2</span>
        <span>3</span>
        <span>4</span>
    </div>
    

    nth-child(2)会选择第2个子元素,而且子元素必须是span,但是没找到(第二个子元素为p)

    .wrap span:nth-child(3){
        color:red;
    }
    

    nth-child(3)会选择第3个子元素,而且子元素必须是span

    相关

    • nth-last-child(n) 从后往前找子元素

    nth-of-type(n)

    //选择父元素下的第二个span
    .wrap span:nth-of-type(2){
        color:red;
    }
    

    同样的html,nth-of-type(2) 会找到子元素的第2个span,不管有没有其他元素阻碍

    相关

    • nth-last-of-type(n) 从后往前找子元素

    only-child

    <div class="wrap">
        <span>1</span>
    </div> 
    
    /*css*/
    .wrap span:only-child{
        color:red;
    }
    
    

    只有父元素下有一个子元素时,才会生效
    当有其他任意标签时,不生效

    only-child应用比较少

    相关

    • last-child 最后一个子元素

    only-of-type

    对比于only-child,only-of-type允许父元素下有其他类的子元素

    // 这时会选中唯一的span元素
    <div class="wrap">
        <span>1</span>
        <i>2</i>
    </div> 
    .wrap span:only-of-type{
        color:red;
    }
    
    

    相关

    • first-of-type 选中第一个指定子元素
    • last-of-type 选中最后一个指定子元素
  • 相关阅读:
    月亮的背后
    2007经典妙语100句
    2007经典妙语100句
    VS C++ 2005的预生成事件及设置
    user case VS. user story
    如何用正确的方法来写出质量好的软件的75条体会
    用 Lucene 加速 Web 搜索应用程序的开发
    巾帼不让须眉——女生做运维 interesting topic
    ebean
    Download the 2.0.0 Release of the Scala IDE for Eclipse Scala IDE for Eclipse
  • 原文地址:https://www.cnblogs.com/zhangceblogs/p/8358846.html
Copyright © 2011-2022 走看看