zoukankan      html  css  js  c++  java
  • CSS根据子元素个数不同定义样式

      近日面试,遇见了一个这样的问题,不会,便记下来。

      问题:如何根据子元素个数的不同定义不同的样式?

      代码:HTML

    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
    
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
    </ul>

      CSS:

    /* one item */
    li:first-child:nth-last-child(1) {
        width: 100%;
    }
    /* two items */
    li:first-child:nth-last-child(2),
    li:first-child:nth-last-child(2) ~ li {
        width: 50%;
    }
    /* three items */
    li:first-child:nth-last-child(3),
    li:first-child:nth-last-child(3) ~ li {
        width: 33.3333%;
    }
    /* four items */
    li:first-child:nth-last-child(4),
    li:first-child:nth-last-child(4) ~ li {
        width: 25%;
    }

      结果:

      解释:

      li:first-child 选择作为第一个子元素的li
      :nth-last-child(n) 选择倒数第n个元素
      ~ li 选择之后的兄弟li元素
      所以:li:first-child:nth-last-child(3) ~ li,选择的是:作为第一个,并且是倒数第三个的元素(保证了他们的父元素具有3个子元素)之后的兄弟li元素。

                                                                            完结。
    参考链接:http://lightcss.com/styling-children-based-on-their-number-with-css3/#toc-3
  • 相关阅读:
    CG——Grab Cut
    asm2
    preinit_array
    tensorflow aot
    搭建elk
    Linux sed之正则表达式:sed替换字符串时,使用正则表达式的注意事项
    sed:在匹配模式的行首或者行尾插入字符
    logical exclusive 与 physical exclusive 的区别
    logical exclusive 与 physical exclusive 的区别
    ztSpyGlass工具介绍_focus357的博客-程序员宅基地
  • 原文地址:https://www.cnblogs.com/mdengcc/p/6672186.html
Copyright © 2011-2022 走看看