TIL - CSS Specificity(명시도) 정리
Specificity (명시도)
CSS를 적용하다 보면 같은 요소에 confilcts 가 발생할 수 있고, specificity는 브라우저로 하여금 해당 요소와 가장 연관된 속성이 적용될 수 있도록 합니다. specificity는 CSS selector에 따라 다음과 같이 우선순위를 판단한다.
4️⃣ type < 3️⃣ class < 2️⃣ id < 1️⃣ inline < 0️⃣ !important
👉 type vs class
<style>
h1 {
color: green;
}
.pink-text {
color: pink;
}
</style>
<h1>GREEN or PINK?</h1> // green
<h1 class="pink-text">GREEN or PINK?</h1> // pink
👉 class vs id
<style>
.green-text {
color: green;
}
#pink-text {
color: pink;
}
</style>
<h1 class="green-text">GREEN or PINK?</h1> // green
<h1 id="pink-text" class="green-text">GREEN or PINK?</h1> // pink
👉 id vs inline
<style>
#green-text {
color: green;
}
</style>
<h1 id="green-text">GREEN or PINK?</h1> // green
<h1 id="green-text" style="color: pink">GREEN or PINK?</h1> // pink
👉 inline vs !important
앞서 본 여러 override 케이스를 통하여 가장 높은 명시도를 가지고 있는 것은 inline style 이다. 그러나 !important규칙이 선언되는 경우, 예외를 만들 수 있다.
<style>
#green-text {
color: green !important;
}
</style>
<h1 id="green-text" style="color: pink;">GREEN or PINK?</h1> // green
id에 !important규칙을 선언하여 inline style보다 명시도가 낮음에도 id선택자의 속성값이 반영되었다. 향후 CSS로 작업하다 보면 CSS라이브러리 등을 사용할 수 있는데, 이 때 자신이 직접 설정해 놓은 CSS마저 바뀌어 버리는 경우가 있다고 한다. 이렇게 자신이 설정한 고유의 CSS를 고수하여야 하는 경우에는 !important규칙을 사용하여 원치않는 변경을 방지할 수 있다고 한다.
Author And Source
이 문제에 관하여(TIL - CSS Specificity(명시도) 정리), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@geeonie/TIL-CSS-Specificity명시도-정리저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)