:only-child (Selectors) – CSS 中文开发手册

[
  •   CSS 中文开发手册

    :only-child (Selectors) - CSS 中文开发手册

    该:only-childCSS伪类表示没有任何同胞元素的元素。这与:first-child:last-child或:nth-child(1):nth-last-child(1)相同的,但具有较低的特异性。

    /* Selects each <p>, but only if it is the */
    /* only child of its parent */
    p:only-child {
      background-color: lime;
    }

    注意:如最初定义的那样,所选元素必须有一个父元素。但从选择器级别4开始,这不再是必需的。

    语法

    :only-child

    实例

    基本实例

    HTML

    <main>
      <div>
        <i>I am a lonely only child.</i>
      </div>
    
      <div>
        <i>I have siblings.</i><br>
        <b>So do I!</b><br>
        <span>I also have siblings, <span>but this is an only child.</span></span>
      </div>
    </main>

    CSS

    main :only-child {
      color: red;
    }

    结果

    列表示例

    HTML

    <ol>
      <li>First
        <ul>
          <li>This list has just one element.
        </ul>
      </li>
      <li>Second
        <ul>
          <li>This list has three elements.
          <li>This list has three elements.
          <li>This list has three elements.
        </ul>
      </li>
    <ol>

    CSS

    li li {
      list-style-type: disc;
    }
    li:only-child {
      color: red;
      list-style-type: square;
    }

    结果

    规范

    Specification

    Status

    Comment

    Selectors Level 4The definition of ':only-child' in that specification.

    Working Draft

    Matching elements are not required to have a parent.

    Selectors Level 3The definition of ':only-child' in that specification.

    Recommendation

    Initial definition.

    浏览器兼容性

    Feature

    Chrome

    Edge

    Firefox (Gecko)

    Internet Explorer

    Opera

    Safari

    Basic support

    2

    (Yes)

    1.5 (1.8)

    9

    9.5

    3.1

    No parent required

    57

    ?

    ?

    ?

    44

    ?

    Feature

    Android Webview

    Chrome for Android

    Edge

    Firefox Mobile (Gecko)

    IE Mobile

    Opera Mobile

    Safari Mobile

    Basic support

    (Yes)

    (Yes)

    (Yes)

    1.0 (1.8)

    9

    10

    3.1

    No parent required

    57

    57

    ?

    ?

    ?

    44

    ?

  •   CSS 中文开发手册
    ]
    转载请保留页面地址:https://www.breakyizhan.com/css/31253.html
    原文地址:https://www.cnblogs.com/breakyizhan/p/13281256.html