Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dark Mode Link Contrast HTML/CSS

I’m a false beginner with HTML, CSS, and Javascript (having done KhanAcademy stuff in the past but also having forgotten most of it). I’m working on trying to get a simple webpage with dark mode going (with as little Javascript as possible). The problem is, the links have low contrast in dark mode. I’m using this code to add a class of .dark-mode to the body element of my html and style it with CSS.

Javascript:

function myFunction() {
    var element = document.body;
    element.classList.toggle("dark-mode");
 }

CSS:

html, body {
    background-color: ivory;
    color: black;
}

.dark-mode {
  background-color: #142514;
  color: blanchedalmond;
}

button.right {
    float: right;
}

HTML:

<button class="right" onclick="myFunction()">Toggle Dark Mode</button>

I tried adding this to CSS, but I realize that the tag isn’t getting class="dark-mode".

CSS:

a.dark-mode:link { color: lightskyblue; }
a.dark-mode:visited { color: #6d4b8d; }
a.dark-mode:hover { color: #ffffff; }
a.dark-mode:active { color: #ff4040; text-decoration:none; font-weight:normal; }

Could someone please help me figure out a method that is light on Javascript to either add the dark-mode class to the tag as well as to the body or specify that the tag should get these attributes when the body has the dark-mode class? Any help would be greatly appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem is that you are toggling a .dark-mode class on your <body/> element, but you are writing your CSS selectors as though they themselves would have a .dark-mode class.

This selector:

a.dark-mode {}

…would target an element that looks like this:

<a href="mysite.com" class="dark-mode">Link</a>

Because you want to target all anchors inside a <body/> with a class of .dark-mode you’ll want to rewrite your selectors as:

.dark-mode a:link { color: lightskyblue; }
.dark-mode a:visited { color: #6d4b8d; }
.dark-mode a:hover { color: #ffffff; }
.dark-mode a:active { color: #ff4040; text-decoration:none; font-weight:normal; }

…which matches all anchors inside an element with class .dark-mode.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading