CSS 中的 Fizz Buzz
Fizz Buzz in CSS

原始链接: https://susam.net/fizz-buzz-in-css.html

苏萨姆·帕尔展示了一种仅使用CSS的解决方案来解决经典的FizzBuzz问题,仅用四行CSS代码即可实现序列输出。该代码利用CSS计数器和`:nth-child()`选择器在列表(`

  • `)元素内生成序列。 具体来说,它为每个列表项递增计数器,除非该项能被5整除,否则显示计数器值,为3的倍数添加前缀“Fizz”,为5的倍数添加后缀“Buzz”。 作者承认该解决方案并非针对代码高尔夫优化,而是将其作为起点提供。提供了一个精简版的代码,去除了所有空格,长度为152个字符。帕尔邀请读者提交更短、更高效的解决方案。一个可运行的示例可在css-fizz-buzz.html找到。

    一位 Hacker News 用户 susam 分享了一个仅使用 CSS 解决经典 FizzBuzz 问题的创意方案。该方法利用有序列表 (`
      `) 和 CSS 选择器 (`:nth-child()`) 来显示“Fizz”(3 的倍数)、“Buzz”(5 的倍数),并隐藏列表样式。 虽然代码简洁(129 个字符的 CSS),susam 提到输出显示错位。一位评论者建议使用 `list-style-position: inside;` 来改善对齐。 其他用户认为这个方案巧妙而有趣,承认它不是传统的编程解决方案。一位评论员指出,由于必要的 HTML 开销,它不适合“代码高尔夫”,特别是当扩展到更大的数字集合时,实际实现需要 JavaScript。 这篇帖子引发了关于替代方案以及“真正”解决方案定义的讨论。
  • 相关文章

    原文
    Fizz Buzz in CSS - Susam Pal

    By Susam Pal on 06 Dec 2025

    What is the smallest CSS code we can write to print the Fizz Buzz sequence? I think it can be done in four lines of CSS as shown below:

    li { counter-increment: n }
    li:not(:nth-child(5n))::before { content: counter(n) }
    li:nth-child(3n)::before { content: "Fizz" }
    li:nth-child(5n)::after { content: "Buzz" }
    

    Here is a complete working example: css-fizz-buzz.html.

    I am neither a web developer nor a code-golfer. Seasoned code-golfers looking for a challenge can probably shrink this solution further. However, such wizards are also likely to scoff at any mention of counting lines of code, since CSS can be collapsed into a single line. The number of characters is probably more meaningful. The code can also be minified slightly by removing all whitespace:

    $ curl -sS https://susam.net/css-fizz-buzz.html | sed -n '/counter/,/after/p' | tr -d '[:space:]'
    li{counter-increment:n}li:not(:nth-child(5n))::before{content:counter(n)}li:nth-child(3n)::before{content:"Fizz"}li:nth-child(5n)::after{content:"Buzz"}

    This minified version is composed of 152 characters:

    $ curl -sS https://susam.net/css-fizz-buzz.html | sed -n '/counter/,/after/p' | tr -d '[:space:]' | wc -c
    152

    If you manage to create a shorter solution, please do leave a comment.

    联系我们 contact @ memedata.com