Как применить Темную тему с помощью CSS-файла

#javascript #html #css #themes

Вопрос:

У меня есть этот код

 /* Themes.css */
:root {
    --headerBG: #222;
    --headerColor: #fff;
    --codeBoxBG: #333;
    --codeBoxColor: #fff;
    --codeHeaderBG: #121212;
    --codeColor: #fff;
    --bodyBG: #ccc;
    --bodyColor: #000;
    --linkColor: #ccc;
    --linkHover: #000;
}


/* Styles.css */
@import url('https://fonts.googleapis.com/css2?family=Georama:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900amp;display=swap');

* { box-sizing: border-box; margin: 0; padding: 0; transition: all .2s ease-in-out; }
body { font-family: 'Georama', sans-serif; width: 100%; background: var(--bodyBG); color: var(--bodyColor); }

header {
    background-color: var(--headerBG);
    min-height: 300px; min-width: 100vw;
    color: var(--headerColor);
    display: block;
    margin-left: auto;
    margin-right: auto;
    text-align: left;
    padding: 80px 180px 50px 180px;
}

article { padding: 80px 180px 50px 180px; }
header h1 { font-size: 2.2em; margin-bottom: 10px; }
header h2 { font-size: 1.2em; margin-bottom: 30px; }
header a, nav a { color: #ccc; text-decoration: none; }
a:hover { color: #00aeff; }
p { margin-bottom: 8px; }
img { max-width: 100%; display: block; margin: 20px auto; }
article a { color: var(--linkColor); text-decoration: none; }
article a:hover { color: var(--linkHover); }

nav {
    height: 50px; padding: 15px;
    width: 100%; color: #fff;
    background-color: #535353;
    align-items: center;
}

nav a { margin: auto 3px; }
nav .items { float: right; }

.heading { margin-bottom: 10px; }
.heading2 { margin-top: 20px; margin-bottom: 10px; }

hr { margin: 30px auto; }
hr.hr1{ border-top: 3px solid #8c8b8b; }
hr.hr2 { border-top: 5px solid #8c8b8b; }

.codebox {
    padding: 10px;
    font-size: 1em;
    line-height: 1.3;
    color: var(--codeBoxColor);
    background-color: var(--codeBoxBG);
    border-radius: 0px 0px 6px 6px;
    margin-bottom: 10px;
    overflow: auto;
}

code { font-size: 1em; line-height: 1.3; }

.codeheader {
    padding: 5px 5px 5px 10px;
    font-size: 1.1em;
    color: var(--codeColor);
    border-radius: 6px 6px 0px 0px;
    user-select: none;
    background: var(--codeHeaderBG);
    border-bottom: 2px solid #00aeff;
}

.codeheader div {
    margin-top: 3px;
    height: .6em; width: .6em;
    background: #fff;
    border-radius: 50%;
    display: inline-block;
}

.codeheader div:first-child { background: #ff4a4a; }
.codeheader div:nth-child(2) { background: #ffc64a; }
.codeheader div:last-child { margin-right: 6px; background: #59ff4a; } 
 <!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css">
<link rel="stylesheet" href="themes.css">
<link rel="stylesheet" href="styles.css">

<nav>
    <span class="brand">
        MyBlog.com
    </span>
    <div class="items">
        <a class="active" href="#">Home</a>
        <a href="#">About</a>
        <a href="#">Contact</a>
    </div>
</nav>

<header>
    <h1>Man must explore, and this is exploration at its greatest</h1>
    <h2 class="subheading">Problems look mighty small from 150 miles up</h2>
    <span class="meta">
        Posted by
        <a href="#!">Start Bootstrap</a>
        on August 24, 2021
    </span>
</header>

<article>
    <h2 class="heading">The Lorem and Ipsum</h2>
    <p>Never in all their history have men been able truly to conceive of the world as one: a single sphere, a globe, having the qualities of a globe, a round earth in which all the directions eventually meet, in which there is no center because every point, or none, is center — an equal earth which all men occupy as equals. The airman's earth, if free men make it, will be truly round: a globe in practice, not in theory.</p>
    <p>Science cuts two ways, of course; its products can be used for both good and evil. But there's no turning back from science. The early warnings about technological dangers also come from science.</p>
    <p>What was most significant about the lunar voyage was not that man set foot on the Moon but that they set eye on the earth.</p>
    <p>A Chinese tale tells of some men sent to harm a young girl who, upon seeing her beauty, become her protectors rather than her violators. That's how I felt seeing the Earth for the first time. I could not help but love and cherish her.</p>
    <p>For those who have seen the Earth from space, and for the hundreds and perhaps thousands more who will, the experience most certainly changes your perspective. The things that we share in our world are far more valuable than those which divide us.</p>

<div class="codeheader">
    <div></div>
    <div></div>
    <div></div>
    css
</div>
<div class="codebox">
<pre><code>.somecssclass {
  padding: 15px;
  font-family: Courier, sans-serif;
  font-size: 12px;
  color: #fff;
  background-color: #3d3d3d;
  margin-bottom: 10px;
  -webkit-border-radius: 0px 0px 6px 6px;
  -moz-border-radius: 0px 0px 6px 6px;
  border-radius: 0px 0px 6px 6px;
}</code></pre>
</div>

    <hr class="hr1">

    <h2 class="heading2">The Final Frontier</h2>
    <p>There can be no thought of finishing for ‘aiming for the stars.’ Both figuratively and literally, it is a task to occupy the generations. And no matter how much progress one makes, there is always the thrill of just beginning.</p>
    <p>There can be no thought of finishing for ‘aiming for the stars.’ Both figuratively and literally, it is a task to occupy the generations. And no matter how much progress one makes, there is always the thrill of just beginning.</p>
    <blockquote class="blockquote">The dreams of yesterday are the hopes of today and the reality of tomorrow. Science has not yet mastered prophecy. We predict too much for the next year and yet far too little for the next ten.</blockquote>
    <p>Spaceflights cannot be stopped. This is not the work of any one man or even a group of men. It is a historical process which mankind is carrying out in accordance with the natural laws of human development.</p>

    <hr class="hr2">

    <h2 class="heading2">Reaching for the Stars</h2>
    <p>As we got further and further away, it [the Earth] diminished in size. Finally it shrank to the size of a marble, the most beautiful you can imagine. That beautiful, warm, living object looked so fragile, so delicate, that if you touched it with a finger it would crumble and fall apart. Seeing this has to change a man.</p>
    <a href="#!"><img class="img-fluid" src="assets/img/post-sample-image.jpg" alt="..." /></a>
    <span class="caption text-muted">To go places and do things that have never been done before – that’s what living is all about.</span>
    <p>Space, the final frontier. These are the voyages of the Starship Enterprise. Its five-year mission: to explore strange new worlds, to seek out new life and new civilizations, to boldly go where no man has gone before.</p>
    <p>As I stand out here in the wonders of the unknown at Hadley, I sort of realize there’s a fundamental truth to our nature, Man must explore, and this is exploration at its greatest.</p>
    <p>Placeholder text by <a href="#">Space Ipsum</a> amp;middot; Images by <a href="#">NASA on The Commons</a></p>
</article> 

Где у меня есть файл с именем styles.css , в котором у меня есть весь код, а также файл с именем themes.css в themes.css файле, у меня есть все цвета, определенные в этом файле, но есть ли способ изменить этот цвет с помощью javascript, чтобы я мог изменить тему ?

Например, когда у меня есть Светлая тема, я Использую эти цвета

 :root {
    --headerBG: #222;
    --headerColor: #fff;
    --codeBoxBG: #333;
    --codeBoxColor: #fff;
    --codeHeaderBG: #121212;
    --codeColor: #fff;
    --bodyBG: #ccc;
    --bodyColor: #000;
    --linkColor: #ccc;
    --linkHover: #000;
}
 

И когда у меня выбрана Темная тема, цвета должны быть

 :root {
    --headerBG: #222;
    --headerColor: #fff;
    --codeBoxBG: #222;
    --codeBoxColor: #fff;
    --codeHeaderBG: #121212;
    --codeColor: #fff;
    --bodyBG: #333;
    --bodyColor: #fff;
    --linkColor: #e7e7e7;
    --linkHover: #fff;
}
 

Комментарии:

1. переопределите темные цвета в каком-нибудь другом классе , например dark , а затем используйте js, чтобы прикрепить этот класс к html body элементу или

2. можете ли вы привести какой-нибудь пример, которого я не понял

3. :root {--mycolor: red} , затем создайте новый класс .dark {--mycolor: blue} . Теперь, если вы установите <body class="dark">... , он будет принимать цвета из темного класса. надеюсь, в этом есть смысл

4. может быть, это поможет прояснить ситуацию css-tricks.com/a-complete-guide-to-dark-mode-on-the-web/…

5. Большое спасибо, что это сработало с использованием классов

Ответ №1:

Определите класс, например

 .myroot {
    --headerBG: yellow;
}
 

и применяйте этот класс там, где вам нужно, через

 class="myroot"
 

Видеть:

 /* Themes.css */
:root {
    --headerBG: #222;
    --headerColor: #fff;
    --codeBoxBG: #333;
    --codeBoxColor: #fff;
    --codeHeaderBG: #121212;
    --codeColor: #fff;
    --bodyBG: #ccc;
    --bodyColor: #000;
    --linkColor: #ccc;
    --linkHover: #000;
}

.myroot {
    --headerBG: yellow;
}


/* Styles.css */
@import url('https://fonts.googleapis.com/css2?family=Georama:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900amp;display=swap');

* { box-sizing: border-box; margin: 0; padding: 0; transition: all .2s ease-in-out; }
body { font-family: 'Georama', sans-serif; width: 100%; background: var(--bodyBG); color: var(--bodyColor); }

header {
    background-color: var(--headerBG);
    min-height: 300px; min-width: 100vw;
    color: var(--headerColor);
    display: block;
    margin-left: auto;
    margin-right: auto;
    text-align: left;
    padding: 80px 180px 50px 180px;
}

article { padding: 80px 180px 50px 180px; }
header h1 { font-size: 2.2em; margin-bottom: 10px; }
header h2 { font-size: 1.2em; margin-bottom: 30px; }
header a, nav a { color: #ccc; text-decoration: none; }
a:hover { color: #00aeff; }
p { margin-bottom: 8px; }
img { max-width: 100%; display: block; margin: 20px auto; }
article a { color: var(--linkColor); text-decoration: none; }
article a:hover { color: var(--linkHover); }

nav {
    height: 50px; padding: 15px;
    width: 100%; color: #fff;
    background-color: #535353;
    align-items: center;
}

nav a { margin: auto 3px; }
nav .items { float: right; }

.heading { margin-bottom: 10px; }
.heading2 { margin-top: 20px; margin-bottom: 10px; }

hr { margin: 30px auto; }
hr.hr1{ border-top: 3px solid #8c8b8b; }
hr.hr2 { border-top: 5px solid #8c8b8b; }

.codebox {
    padding: 10px;
    font-size: 1em;
    line-height: 1.3;
    color: var(--codeBoxColor);
    background-color: var(--codeBoxBG);
    border-radius: 0px 0px 6px 6px;
    margin-bottom: 10px;
    overflow: auto;
}

code { font-size: 1em; line-height: 1.3; }

.codeheader {
    padding: 5px 5px 5px 10px;
    font-size: 1.1em;
    color: var(--codeColor);
    border-radius: 6px 6px 0px 0px;
    user-select: none;
    background: var(--codeHeaderBG);
    border-bottom: 2px solid #00aeff;
}

.codeheader div {
    margin-top: 3px;
    height: .6em; width: .6em;
    background: #fff;
    border-radius: 50%;
    display: inline-block;
}

.codeheader div:first-child { background: #ff4a4a; }
.codeheader div:nth-child(2) { background: #ffc64a; }
.codeheader div:last-child { margin-right: 6px; background: #59ff4a; } 
 <!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css">
<link rel="stylesheet" href="themes.css">
<link rel="stylesheet" href="styles.css">

<nav>
    <span class="brand">
        MyBlog.com
    </span>
    <div class="items">
        <a class="active" href="#">Home</a>
        <a href="#">About</a>
        <a href="#">Contact</a>
    </div>
</nav>

<header class="myroot">
    <h1>Man must explore, and this is exploration at its greatest</h1>
    <h2 class="subheading">Problems look mighty small from 150 miles up</h2>
    <span class="meta">
        Posted by
        <a href="#!">Start Bootstrap</a>
        on August 24, 2021
    </span>
</header>

<article>
    <h2 class="heading">The Lorem and Ipsum</h2>
    <p>Never in all their history have men been able truly to conceive of the world as one: a single sphere, a globe, having the qualities of a globe, a round earth in which all the directions eventually meet, in which there is no center because every point, or none, is center — an equal earth which all men occupy as equals. The airman's earth, if free men make it, will be truly round: a globe in practice, not in theory.</p>
    <p>Science cuts two ways, of course; its products can be used for both good and evil. But there's no turning back from science. The early warnings about technological dangers also come from science.</p>
    <p>What was most significant about the lunar voyage was not that man set foot on the Moon but that they set eye on the earth.</p>
    <p>A Chinese tale tells of some men sent to harm a young girl who, upon seeing her beauty, become her protectors rather than her violators. That's how I felt seeing the Earth for the first time. I could not help but love and cherish her.</p>
    <p>For those who have seen the Earth from space, and for the hundreds and perhaps thousands more who will, the experience most certainly changes your perspective. The things that we share in our world are far more valuable than those which divide us.</p>

<div class="codeheader">
    <div></div>
    <div></div>
    <div></div>
    css
</div>
<div class="codebox">
<pre><code>.somecssclass {
  padding: 15px;
  font-family: Courier, sans-serif;
  font-size: 12px;
  color: #fff;
  background-color: #3d3d3d;
  margin-bottom: 10px;
  -webkit-border-radius: 0px 0px 6px 6px;
  -moz-border-radius: 0px 0px 6px 6px;
  border-radius: 0px 0px 6px 6px;
}</code></pre>
</div>

    <hr class="hr1">

    <h2 class="heading2">The Final Frontier</h2>
    <p>There can be no thought of finishing for ‘aiming for the stars.’ Both figuratively and literally, it is a task to occupy the generations. And no matter how much progress one makes, there is always the thrill of just beginning.</p>
    <p>There can be no thought of finishing for ‘aiming for the stars.’ Both figuratively and literally, it is a task to occupy the generations. And no matter how much progress one makes, there is always the thrill of just beginning.</p>
    <blockquote class="blockquote">The dreams of yesterday are the hopes of today and the reality of tomorrow. Science has not yet mastered prophecy. We predict too much for the next year and yet far too little for the next ten.</blockquote>
    <p>Spaceflights cannot be stopped. This is not the work of any one man or even a group of men. It is a historical process which mankind is carrying out in accordance with the natural laws of human development.</p>

    <hr class="hr2">

    <h2 class="heading2">Reaching for the Stars</h2>
    <p>As we got further and further away, it [the Earth] diminished in size. Finally it shrank to the size of a marble, the most beautiful you can imagine. That beautiful, warm, living object looked so fragile, so delicate, that if you touched it with a finger it would crumble and fall apart. Seeing this has to change a man.</p>
    <a href="#!"><img class="img-fluid" src="assets/img/post-sample-image.jpg" alt="..." /></a>
    <span class="caption text-muted">To go places and do things that have never been done before – that’s what living is all about.</span>
    <p>Space, the final frontier. These are the voyages of the Starship Enterprise. Its five-year mission: to explore strange new worlds, to seek out new life and new civilizations, to boldly go where no man has gone before.</p>
    <p>As I stand out here in the wonders of the unknown at Hadley, I sort of realize there’s a fundamental truth to our nature, Man must explore, and this is exploration at its greatest.</p>
    <p>Placeholder text by <a href="#">Space Ipsum</a> amp;middot; Images by <a href="#">NASA on The Commons</a></p>
</article> 

Ответ №2:

Однострочный код преобразует светлую тему в темную. Попробовать это

 <style>
body
{
  filter: invert(1);
}
</style>
 

Комментарии:

1. Это хорошая идея, но она не является ответом на вопрос.