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
  • 相关阅读:
    Metropolis-Hastings algorithm
    Base64编码原理
    修改远程端口号
    修改数据库配置文件
    Windows 2008下系统网站运行环境的搭建
    oracle 11 g数据库卸载(方法二)
    oracle11g的安装
    oracle 11g的卸载
    软件实施的技巧
    使用命令行快速打开系统文件
  • 原文地址:https://www.cnblogs.com/mdengcc/p/6672186.html
Copyright © 2011-2022 走看看