
CSS ile sayfalarımızı güzelleştiriyoruz. Peki ya kullanıcı bir butona tıkladığında rengi değiştirmek istersek? Ya da bir elementi dinamik olarak gizlemek/göstermek istersek?
JavaScript ile elementlerin CSS stillerini okuyabilir ve değiştirebilirsiniz. Bu makalede style property'si ve getComputedStyle metodunu öğreneceğiz.
style Property'si
Her elementin bir style property'si vardır. Bu property üzerinden inline stil ekleyebilirsiniz.
Temel Kullanım
const element = document.querySelector("#kutu");
// Stil değiştirme
element.style.color = "red";
element.style.backgroundColor = "yellow";
element.style.fontSize = "20px";HTML'deki Karşılığı
JavaScript ile eklenen stiller inline style olarak eklenir:
element.style.color = "red";
element.style.padding = "10px";Bu kod şuna eşdeğerdir:
<div style="color: red; padding: 10px;">...</div>CSS Property İsimlendirmesi
CSS'te tire (-) ile yazılan property'ler JavaScript'te camelCase yazılır:
| CSS | JavaScript |
|---|---|
background-color | backgroundColor |
font-size | fontSize |
border-radius | borderRadius |
margin-top | marginTop |
text-decoration | textDecoration |
z-index | zIndex |
box-shadow | boxShadow |
Örnekler
const kutu = document.querySelector(".kutu");
// CSS: background-color → JS: backgroundColor
kutu.style.backgroundColor = "lightblue";
// CSS: font-size → JS: fontSize
kutu.style.fontSize = "18px";
// CSS: border-radius → JS: borderRadius
kutu.style.borderRadius = "10px";
// CSS: margin-top → JS: marginTop
kutu.style.marginTop = "20px";
// CSS: text-align → JS: textAlign
kutu.style.textAlign = "center";Tire Kullanırsanız Hata Alırsınız!
// ❌ YANLIŞ - Hata verir
kutu.style.background-color = "red"; // SyntaxError
// ✅ DOĞRU
kutu.style.backgroundColor = "red";Değer Formatı
Stil değerleri string olarak verilmelidir ve gerekli birimler dahil edilmelidir:
// ✅ Doğru - birim dahil
element.style.width = "200px";
element.style.fontSize = "1.5rem";
element.style.marginTop = "2em";
element.style.opacity = "0.5"; // Birimsiz değerler de string
// ❌ Yanlış - birim yok
element.style.width = 200; // Çalışmaz!
element.style.fontSize = 1.5; // Çalışmaz!Stil Okuma
style property'si sadece inline stilleri okuyabilir. CSS dosyasındaki stilleri okuyamaz!
Örnek
<style>
#baslik {
color: blue;
font-size: 24px;
}
</style>
<h1 id="baslik">Merhaba</h1>const baslik = document.querySelector("#baslik");
// CSS dosyasından gelen stili okumaya çalış
console.log(baslik.style.color); // "" (boş string!)
console.log(baslik.style.fontSize); // "" (boş string!)
// Inline stil ekle
baslik.style.color = "red";
// Artık okuyabilirsin (inline olduğu için)
console.log(baslik.style.color); // "red"Neden Boş Döner?
element.style sadece HTML'deki style attribute'unu okur. CSS dosyasındaki veya <style> etiketindeki stilleri görmez.
getComputedStyle()
Bir elementin gerçek/hesaplanmış stilini okumak için getComputedStyle() kullanılır:
Sözdizimi
window.getComputedStyle(element)Örnek
<style>
#kutu {
width: 200px;
height: 100px;
background-color: coral;
font-size: 16px;
}
</style>
<div id="kutu">İçerik</div>const kutu = document.querySelector("#kutu");
// style ile okuma (CSS'ten gelen stiller görünmez)
console.log(kutu.style.width); // "" (boş)
console.log(kutu.style.backgroundColor); // "" (boş)
// getComputedStyle ile okuma (her şeyi görür)
const stiller = window.getComputedStyle(kutu);
console.log(stiller.width); // "200px"
console.log(stiller.backgroundColor); // "rgb(255, 127, 80)"
console.log(stiller.fontSize); // "16px"Önemli Notlar
getComputedStyle()sadece okuma içindir, stil değiştiremezsiniz- Renkler RGB formatında döner
- Tüm değerler string olarak döner
const stiller = window.getComputedStyle(element);
// ❌ Değiştirmeye çalışmak işe yaramaz
stiller.color = "red"; // Hiçbir etkisi yok!
// ✅ Değiştirmek için style kullan
element.style.color = "red";Pratik Örnekler
Örnek 1: Hover Efekti (JavaScript ile)
<div id="kart">Üzerime gel!</div>const kart = document.querySelector("#kart");
// Başlangıç stilleri
kart.style.padding = "20px";
kart.style.backgroundColor = "#f0f0f0";
kart.style.transition = "all 0.3s ease";
kart.style.cursor = "pointer";
// Mouse üzerine gelince
kart.addEventListener("mouseenter", function() {
this.style.backgroundColor = "#007bff";
this.style.color = "white";
this.style.transform = "scale(1.05)";
});
// Mouse ayrılınca
kart.addEventListener("mouseleave", function() {
this.style.backgroundColor = "#f0f0f0";
this.style.color = "black";
this.style.transform = "scale(1)";
});Örnek 2: Karanlık/Aydınlık Mod
<button id="tema-btn">Karanlık Mod</button>const temaBtn = document.querySelector("#tema-btn");
let karanlikMod = false;
temaBtn.addEventListener("click", function() {
if (karanlikMod) {
// Aydınlık moda geç
document.body.style.backgroundColor = "white";
document.body.style.color = "black";
this.innerText = "Karanlık Mod";
} else {
// Karanlık moda geç
document.body.style.backgroundColor = "#1a1a1a";
document.body.style.color = "white";
this.innerText = "Aydınlık Mod";
}
karanlikMod = !karanlikMod;
});Örnek 3: Element Gizle/Göster
<button id="toggle-btn">Gizle</button>
<div id="icerik">Bu içerik gizlenebilir.</div>const toggleBtn = document.querySelector("#toggle-btn");
const icerik = document.querySelector("#icerik");
let gorunur = true;
toggleBtn.addEventListener("click", function() {
if (gorunur) {
icerik.style.display = "none";
this.innerText = "Göster";
} else {
icerik.style.display = "block";
this.innerText = "Gizle";
}
gorunur = !gorunur;
});Örnek 4: Opacity ile Gizleme (Animasyonlu)
const element = document.querySelector("#element");
// CSS'te transition ekle
element.style.transition = "opacity 0.5s ease";
// Gizle (yavaşça kaybolur)
element.style.opacity = "0";
// Göster (yavaşça belirir)
element.style.opacity = "1";Örnek 5: Tüm Linklerin Stilini Değiştirme
const linkler = document.querySelectorAll("a");
linkler.forEach(link => {
link.style.color = "#e91e63";
link.style.textDecoration = "none";
link.style.fontWeight = "bold";
link.style.transition = "color 0.2s";
});Örnek 6: Rastgele Arka Plan Rengi
<button id="renk-btn">Renk Değiştir</button>const renkBtn = document.querySelector("#renk-btn");
function rastgeleRenk() {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
return `rgb(${r}, ${g}, ${b})`;
}
renkBtn.addEventListener("click", function() {
document.body.style.backgroundColor = rastgeleRenk();
});Örnek 7: Boyut Artırma/Azaltma
<div id="kutu">Kutu</div>
<button id="buyut">Büyüt</button>
<button id="kucult">Küçült</button>const kutu = document.querySelector("#kutu");
const buyutBtn = document.querySelector("#buyut");
const kucultBtn = document.querySelector("#kucult");
// Başlangıç boyutu
let boyut = 100;
kutu.style.width = boyut + "px";
kutu.style.height = boyut + "px";
kutu.style.backgroundColor = "coral";
kutu.style.transition = "all 0.3s ease";
buyutBtn.addEventListener("click", function() {
boyut += 20;
kutu.style.width = boyut + "px";
kutu.style.height = boyut + "px";
});
kucultBtn.addEventListener("click", function() {
if (boyut > 20) {
boyut -= 20;
kutu.style.width = boyut + "px";
kutu.style.height = boyut + "px";
}
});Örnek 8: Mevcut Stili Okuyup Değiştirme
const baslik = document.querySelector("h1");
// Mevcut font boyutunu al
const stiller = window.getComputedStyle(baslik);
const mevcutBoyut = parseInt(stiller.fontSize); // "32px" → 32
// %50 büyüt
const yeniBoyut = mevcutBoyut * 1.5;
baslik.style.fontSize = yeniBoyut + "px";Örnek 9: Progress Bar
<div id="progress-container" style="width: 300px; background: #eee; border-radius: 5px;">
<div id="progress-bar" style="width: 0%; height: 20px; background: #4caf50; border-radius: 5px;"></div>
</div>
<button id="basla-btn">Başla</button>const progressBar = document.querySelector("#progress-bar");
const baslaBtn = document.querySelector("#basla-btn");
baslaBtn.addEventListener("click", function() {
let yuzde = 0;
progressBar.style.transition = "width 0.1s linear";
const interval = setInterval(function() {
if (yuzde >= 100) {
clearInterval(interval);
} else {
yuzde++;
progressBar.style.width = yuzde + "%";
}
}, 50);
});Birden Fazla Stil Ekleme
Yöntem 1: Tek Tek Atama
element.style.color = "white";
element.style.backgroundColor = "black";
element.style.padding = "10px";
element.style.borderRadius = "5px";Yöntem 2: cssText Kullanma
Tüm stilleri tek seferde atamak için:
element.style.cssText = "color: white; background-color: black; padding: 10px; border-radius: 5px;";Dikkat: cssText mevcut inline stillerin üzerine yazar!
Yöntem 3: Object.assign (Alternatif)
Object.assign(element.style, {
color: "white",
backgroundColor: "black",
padding: "10px",
borderRadius: "5px"
});Stili Sıfırlama
Bir stili kaldırmak için boş string atayın:
// Stili kaldır
element.style.color = "";
element.style.backgroundColor = "";
// Veya tüm inline stilleri kaldır
element.style.cssText = "";
// Veya removeProperty kullan
element.style.removeProperty("color");
element.style.removeProperty("background-color"); // CSS formatındastyle vs CSS Sınıfları
Birçok stil değişikliği için CSS sınıfları kullanmak daha iyidir:
/* CSS dosyasında */
.vurgulu {
background-color: yellow;
font-weight: bold;
padding: 5px;
}// ❌ Çok fazla inline stil
element.style.backgroundColor = "yellow";
element.style.fontWeight = "bold";
element.style.padding = "5px";
// ✅ Daha temiz - class ekle
element.classList.add("vurgulu");Bir sonraki makalede classList konusunu detaylı öğreneceğiz!
Özet
const element = document.querySelector("#element");
// STİL DEĞİŞTİRME
element.style.color = "red";
element.style.backgroundColor = "yellow";
element.style.fontSize = "20px";
element.style.marginTop = "10px";
// BİRDEN FAZLA STİL
element.style.cssText = "color: red; padding: 10px;";
// STİL OKUMA (sadece inline)
console.log(element.style.color);
// HESAPLANMIŞ STİL OKUMA (tümü)
const stiller = window.getComputedStyle(element);
console.log(stiller.fontSize);
// STİLİ KALDIRMA
element.style.color = "";
element.style.removeProperty("background-color");| Yöntem | Kullanım | Not |
|---|---|---|
element.style.x | Tek stil değiştirme | camelCase kullan |
element.style.cssText | Çoklu stil atama | Üzerine yazar |
getComputedStyle() | Stil okuma | Sadece okuma |
Sırada Ne Var?
style property'si ile inline stil ekledik. Ancak gerçek projelerde genellikle CSS sınıfları kullanılır.
Bir sonraki makalede classList konusunu öğreneceğiz - CSS sınıflarını ekleme, kaldırma ve değiştirme yolları.


