CSS容器查询

https://blog.meowrain.cn/api/i/2024/09/15/Vrn7mB1726413699650603571.webp

https://blog.meowrain.cn/api/i/2024/09/15/8xw46u1726413717937408270.webp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="assests/style.css">

</head>

<body>
    <div class="container">
        <div id="app" style="--day-mode: true;">
            <div class="content">
                <p>Hello,there is test1</p>
            </div>
            <div class="content">
                <p>Hello,there is test1</p>
            </div>
            <div class="content">
                <p>Hello,there is test1</p>
            </div>
        </div>
        <div class="btns">
            <button onclick="toggleToNightMode()">Switch to Night Mode</button>
            <button onclick="toggleToDayMode()">Switch to Day Mode</button>
        </div>
    </div>
    <script src="assests/script.js"></script>
</body>

</html>

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

.container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
#app {
    display: flex;
    flex-direction: row;
}

.content {
    display: flex;
    padding: 20px;
    margin: 20px;
    width: 200px;
    height: 200px;
    transition: background-color 0.5s ease, color 0.5s ease;
    justify-content: center;
    align-items: center;
    /* 增加渐变过渡效果 */
}

@container style(--day-mode: true) {
    .content {
        background-color: bisque;
        color: black;
    }
}

@container style(--dark-mode: true) {
    .content {
        background-color: black;
        color: white;
    }
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
const container = document.querySelector('#app');
console.log(container);


// 切换到夜间模式
function toggleToNightMode() {
  container.style.setProperty('--dark-mode', true);
  container.style.setProperty('--day-mode', false);
}

// 切换到白天模式
function toggleToDayMode() {
  container.style.setProperty('--day-mode', true);
  container.style.setProperty('--dark-mode', false);
}
0%