Koyu tema artık bir lüks değil, beklenti. İyi bir tema anahtarı üç şeyi yapar: sistem tercihini ilk açılışta uygular, kullanıcı seçimini hatırlar ve geçişi yumuşatır. Canlı örnekte düğmeye basarak dene.
<main class="card">
<h1>Merhaba 👋</h1>
<p>Tema seçimin bu sayfada hatırlanır.</p>
<button id="toggle" type="button" aria-pressed="false">Temayı değiştir</button>
</main>:root{--bg:#f8fafc;--fg:#0f172a;--card:#fff;--accent:#6366f1}
:root[data-theme=dark]{--bg:#0b1020;--fg:#e2e8f0;--card:#151b30;--accent:#a5b4fc}
body{margin:0;min-height:100vh;display:grid;place-items:center;background:var(--bg);color:var(--fg);font-family:system-ui,sans-serif;transition:background .3s,color .3s}
.card{background:var(--card);padding:32px 40px;border-radius:20px;box-shadow:0 20px 50px -20px rgba(0,0,0,.35);text-align:center;transition:background .3s}
h1{margin:0 0 8px}p{margin:0 0 20px;opacity:.75}
button{padding:12px 24px;border:0;border-radius:12px;background:var(--accent);color:#fff;font:600 15px system-ui;cursor:pointer}
:root[data-theme=dark] button{color:#0b1020}const root = document.documentElement;
const btn = document.getElementById('toggle');
const saved = (() => { try { return localStorage.getItem('theme'); } catch (e) { return null; } })();
const system = matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
function apply(theme) {
root.dataset.theme = theme;
btn.setAttribute('aria-pressed', theme === 'dark');
try { localStorage.setItem('theme', theme); } catch (e) {}
}
apply(saved || system);
btn.addEventListener('click', () => apply(root.dataset.theme === 'dark' ? 'light' : 'dark'));Püf noktaları
- Renkleri doğrudan yazmak yerine CSS değişkenleri kullan; tema değişimi tek satırda olur.
localStoragebazı gizli pencerelerde hata verir; bu yüzden okuma ve yazmatry/catchiçinde.- Sayfa yanıp sönmesin diye bu betiği mümkünse
<head>içinde, boyamadan önce çalıştır.
<script>
(function () {
try {
var t = localStorage.getItem('theme') ||
(matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
document.documentElement.dataset.theme = t;
} catch (e) {}
})();
</script>
