css列表首尾样式如何分别控制_结合css:first与:last child

:first-child和:last-child可分别选中父容器中首个和末个li元素以设置样式,需确保li是首尾子元素,否则应改用:first-of-type/:last-of-type;二者兼容IE9+及以上。

可以通过 :first-child:last-child 伪类分别选中列表中第一个和最后一个

  • 元素,从而独立设置它们的样式。

    基础用法:直接作用于 li 元素

    确保目标元素确实是其父容器的第一个或最后一个子元素。常见写法如下:

    • ul li:first-child { border-top: 2px solid #333; } —— 给首个列表项加顶部边框
    • ul li:last-child { border-bottom: 2px solid #333; } —— 给末项加底部边框
    • 若想首尾都圆角,可写:ul li:first-child { border-radius: 4px 4px 0 0; }ul li:last-child { border-radius: 0 0 4px 4px; }

    注意父子结构是否匹配

    如果

      内部有其他类型子元素(比如注释、空格文本节点不影响,但

      会影响),:first-child 可能不生效。此时建议:
      • 保持结构干净:只放
        • 改用 :first-of-type:last-of-type 更稳妥,它们按元素类型计算而非位置
        • 例如:ul li:first-of-type 会选中第一个
        • ,即使前面有

          配合其他伪类增强控制力

          可以组合使用实现更精细效果:

          • ul li:first-child:not(:last-child) { margin-top: 10px; } —— 首项且非末项时加顶外边距
          • ul li:last-child:first-child { background: #eee; } —— 当列表仅一项时,同时满足首尾条件,可单独设样式
          • 配合 :hover 做交互:ul li:first-child:hover { transform: scale(1.05); }

          兼容性与现代替代方案

          :first-child:last-child 在所有现代浏览器及 IE9+ 中均支持。如需兼容更老版本 IE,可用 JavaScript 补充;但当前项目基本无需考虑。

          CSS 新增的 :has()(如 ul:has(> li:first-child))暂不适用于此场景,目前仍以 :first-child / :last-child 为主流可靠方案。