Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Cách tạo chế độ Dark/Light cho Website bằng CSS

Giới thiệu

Bằng cách thay đổi màu chữ và màu nền của trang, chúng ta có thể thêm chế độ tối/sáng cho website.

Cú pháp

Cú pháp sau có thể được sử dụng để áp dụng chế độ tối:

Selector { 
  color: white; 
  background-color: black 
}

Ví dụ 1: Chuyển đổi cơ bản

<!DOCTYPE html> 
<html> 
  <head> 
    <style> 
      div { 
        font-size: 1.4em; 
        text-align: center; 
      } 
      .dark { 
        color: white; 
        background-color: black; 
      } 
    </style> 
  </head> 
  <body> 
    <div> 
      <p>Suspendisse eget finibus nulla, a pulvinar est. Suspendisse eget eleifend nibh. In nec massa molestie, vehicula sapien a, consectetur nunc. Aenean at nisl vulputate mi scelerisque commodo nec et mauris. Duis tincidunt auctor posuere.</p> 
      <button id="btn" onclick="change()">Normal Mode</button> 
    </div> 
    <script> 
      let btnText = document.getElementById("btn"); 
      function change() { 
        let btn = document.body; 
        btn.classList.toggle("dark"); 
        if (btnText.innerHTML === "Normal Mode") { 
          btnText.innerHTML = "Dark Mode!"; 
        } else { 
          btnText.innerHTML = "Normal Mode"; 
        }
      } 
    </script> 
  </body> 
</html>

Kết quả hiển thị:

Cách tạo chế độ Dark/Light cho Website bằng CSS

Ví dụ 2: Với hình ảnh

<!DOCTYPE html> 
<html> 
  <head> 
    <style> 
      div { 
        font-size: 1.4em; 
        text-align: center; 
      } 
      .dark { 
        color: white; 
        background-color: black; 
      } 
    </style> 
  </head> 
  <body> 
    <div> 
      <button id="btn" onclick="change()">Normal Mode</button> 
      <p>Duis tincidunt auctor posuere.</p> 
      <img src="https://images.unsplash.com/photo-1610718055968-4e3cf23d96db?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=200&ixlib=rb-1.2.1&q=80&w=200" /> 
    </div> 
    <script> 
      let btnText = document.getElementById("btn"); 
      function change() { 
        let btn = document.body; 
        btn.classList.toggle("dark"); 
        if (btnText.innerHTML === "Normal Mode") { 
          btnText.innerHTML = "Dark Mode!"; 
        } else { 
          btnText.innerHTML = "Normal Mode"; 
        }
      } 
    </script> 
  </body> 
</html>

Kết quả hiển thị:

Cách tạo chế độ Dark/Light cho Website bằng CSS

Cách tạo chế độ Dark/Light cho Website bằng CSS