Chapter 6CSS Tutorial~1 min read
CSS Specificity
कोणता CSS Rule जिंकतो?
एकाच element वर multiple CSS rules असतील तर कोणता apply होतो? हे CSS Specificity ठरवते. Specificity म्हणजे CSS rules चे एक weight system — जास्त weight म्हणजे तो rule जिंकतो.
Problem — कोणता color apply होईल?
html
<style>
* { color: gray; }
h1 { color: pink; }
.title { color: blue; }
#main { color: red; }
</style>
<h1 id="main" class="title" style="color: purple;">
मराठी Tech
</h1>
<!-- उत्तर: purple (inline style जिंकतो!) -->Specificity Hierarchy — कोण जास्त powerful?
- ▸Inline Style (1000 points) — सगळ्यात powerful
- ▸ID Selector (100 points) — #id
- ▸Class / Attribute / Pseudo-class (10 points) — .class, [href], :hover
- ▸Element Selector (1 point) — h1, p, div
- ▸Universal Selector (0 points) — * — सगळ्यात weak
Specificity Calculate करणे
Specificity Calculation — उदाहरण
css
/* <h1 id="title" class="h1">मराठी Tech</h1> */
h1 /* 1 point (element) */
.h1 /* 10 points (class) */
#title /* 100 points (ID) */
/* एकत्र: h1#title.h1 = 1 + 100 + 10 = 111 points */Same Specificity — Position Matters
css
/* Same specificity असेल तर — शेवटचा rule जिंकतो */
p {
color: red; /* पहिला */
}
p {
color: blue; /* हा जिंकतो — नंतर आला */
}!important — Nuclear Option
!important — उदाहरण
css
p {
color: red !important; /* 10,000 points — नेहमी जिंकतो */
}
p {
color: blue; /* हा हरतो */
}
/* Result: red */📌
!important खूप sparingly वापरा. हे debugging कठीण करते आणि code maintain करणे hard होते. जेव्हा styles "काम करत नाहीत" असे वाटते तेव्हा बहुतेक specificity मुळे असते.
✅ Key Points — लक्षात ठेवा
- ▸Specificity: Inline(1000) > ID(100) > Class(10) > Element(1) > *(0)
- ▸जास्त points = तो rule जिंकतो
- ▸Same specificity = नंतर आलेला rule जिंकतो
- ▸!important = 10,000 points — नेहमी जिंकतो, sparingly वापरा
- ▸"CSS काम करत नाही" = बहुतेक specificity problem
0/16 chapters पूर्ण