如何创建允许使用纯 HTML 和 CSS 切换主题的 HTML 文档?

How to create an HTML document that allow switch themes using pure HTML and CSS?

如何使用 HTML 和 CSS 创建允许切换主题的文档? (没有 JavaScript)

我创建了简单的 HTML 文档:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
    <style type="text/css">
        :root { --bg-color: lightgreen; }
        * { background-color: var(--bg-color); }
        /* You can add lines here. */
    </style>
</head>
<body>
    <div>
        <h2 id="theme-1">Theme 1</h2>
        <a href="#theme-1">Theme 1</a>
    </div>
    <div>
        <h2 id="theme-2">Theme 2</h2>
        <a href="#theme-2">Theme 2</a>
    </div>
    <div>
        <h2 id="no-theme">No theme</h2>
        <a href="#no-theme">No theme</a>
    </div>
</body>
</html>

带有 <style> 标签。

我试图插入这个 CSS 代码:

        :has(#theme-1:target) { --bg-color: red; }
        :has(#theme-2:target) { --bg-color: blue; }

但是没有人浏览器支持:has选择器。

然后我试着插入这个:

        #theme-1:target { --bg-color: red; }
        #theme-2:target { --bg-color: blue; }

但它不会改变 <body>background-color。它仅更改 <h2> 个标签。

那么,如何切换主题呢?有可能吗?

有可能:您必须嵌套所有内容(或至少嵌套应取决于主题的所有内容)。例如:

<html lang="en">
  <head>
    <title>Document</title>
    <style type="text/css">
      #theme-1:target{
        background: red;
      }
      #theme-1:target h2{
        font-family: "Verdana";
      }
      #theme-2:target{
        background: blue;
      }
      #theme-2:target h2{
        font-family: "Times New Roman";
      }
    </style>
  </head>
  <body>
    <div id="theme-1"><div id="theme-2">
      <h2>Theme 1</h2>
      <a href="#theme-1">Theme 1</a>    
      <h2>Theme 2</h2>
      <a href="#theme-2">Theme 2</a>    
      <h2 id="no-theme">No theme</h2>
      <a href="#no-theme">No theme</a>
    </div></div>
  </body>
</html>