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 选中最后一个指定子元素
  • 相关阅读:
    Sql to Linq 小工具
    datagridview后台添加列
    datatable之distinct用法
    生成器
    函数练习一
    函数初识
    文件操作练习
    文件操作
    迭代器 递归
    基础数据类型上机题
  • 原文地址:https://www.cnblogs.com/zhangceblogs/p/8358846.html
Copyright © 2011-2022 走看看