英文:
Dark mode changer
问题
我有以下代码:
<!doctype html>
<html>
<head>
</head>
<body>
<div id="color-wrapper">
Hello world
</div>
<input id="dark-mode" type="checkbox">
<label for="dark-mode">Dark mode</label>
</body>
<style>
:root {
--bg: pink;
}
#dark-mode:checked ~ #color-wrapper {
--bg: orange;
}
#color-wrapper {
background: var(--bg);
}
</style>
</html>
它应该在我勾选复选框后更改“Hello world”文本的背景颜色,但实际上没有,颜色始终是粉色。问题在哪里?
英文:
I have the following code:
<!doctype html>
<html>
<head>
</head>
<body>
<div id="color-wrapper">
Hello world
</div>
<input id="dark-mode" type="checkbox">
<label for="dark-mode">Dark mode</label>
</body>
<style>
:root {
--bg: pink;
}
#dark-mode:checked ~ #color-wrapper {
--bg: orange;
}
#color-wrapper {
background: var(--bg);
}
</style>
</html>
It has to change background color of the "Hello world" text then I check the checkbox, but it does not, the color is always pink. What is the problem?
答案1
得分: 3
选择符 ~
选择元素之后的同级元素,因此请更改您的 HTML 元素顺序以修复:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
:root {
--bg: pink;
}
#dark-mode:checked ~ #color-wrapper {
--bg: orange;
}
#color-wrapper {
background: var(--bg);
}
<!-- language: lang-html -->
<input id="dark-mode" type="checkbox">
<label for="dark-mode">Dark mode</label>
<div id="color-wrapper">
Hello world
</div>
<!-- end snippet -->
英文:
The tilde selector ~
selects siblings after the element, so change order of elements in your html to fix:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
:root {
--bg: pink;
}
#dark-mode:checked ~ #color-wrapper {
--bg: orange;
}
#color-wrapper {
background: var(--bg);
}
<!-- language: lang-html -->
<input id="dark-mode" type="checkbox">
<label for="dark-mode">Dark mode</label>
<div id="color-wrapper">
Hello world
</div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论