프로그래밍/CSS
22 CSS의 우선순위 계산
윤지(●'◡'●)
2021. 5. 11. 10:12
728x90
반응형
CSS의 우선순위
0순위. !important가 적용된 속성
선택자{속성명: 속성값 !important;}
1. 인라인(요소에 직접 style 속성을 적용하는 것) -> 1000점
<p style="color: red">안녕</p>
2. id 속성 -> 100점
<p id="user">안녕</p>
3. class 속성, 속성 선택자 -> 10점
<p class="user">안녕</p>
<img src="apple.png"><!--src를 사용-->
4. element -> 1점
<p>안녕</p>
* 동일한 선택자일 경우 나중에 적용한 것이 우선시 된다.
문제를 하나 풀어보자!
<style>
#id-style-with-important{background-color: yellow !important;}
#id-style{ background-color: blue;}
#id-style-2{
background-color: skyblue;
margin: 50px;
padding: 50px;
}
.class-style{
background-color: red;
}
div{
display: block;
padding: 30px;
margin: 30px;
background-color: white;
}
div{
background-color: purple;
}
ul>li.li-class{
background-color: salmon;
color: deeppink;
}
ul{
color:black
}
ul >li {color:aqua}
</style>
<body>
<h2>CSS 우선순위</h2>
<div id="id-style-with-important" style="background-color: green;" id="id-style" class="class-style">div 1번</div>
<div style="background-color: green;" id="id-style" class="class-style">div 2번</div>
<div id="id-style">div 3번</div>
<div class="class-style">div 4번</div>
<div>div 5번</div>
<div id="id-style-2" id="id-style">div 6번</div>
<ul>
<li class="li-class">li 1번</li>
</ul>
</body>
위와 같은 코드가 있을 때 각 각 div의 색깔은 어떤 색일까?
결과는 바로!
생각한 결과랑 동일 했나요? (●'◡'●)
풀이
<body>
<h2>CSS 우선순위</h2>
<div id="id-style-with-important" style="background-color: green;" id="id-style" class="class-style">div 1번</div>
<!--!important가 적용되어 yellow-->
<div style="background-color: green;" id="id-style" class="class-style">div 2번</div>
<!--inline 스타일 적용되어 green-->
<div id="id-style">div 3번</div>
<!--id 스타일 적용되어 blue
id: 100점 element(div): 1점-->
<div class="class-style">div 4번</div>
<!--class 스타일 적용되어 red
class: 10점 element(div): 1점-->
<div>div 5번</div>
<!--element(div)가 두개지만 나중에
적용한것이 우선시 되어 purple-->
<div id="id-style-2" id="id-style">div 6번</div>
<!--id나 class 속성은 먼저 적용한 스타일이 우선 적용된다
그래서 id-style-2 스타일 적용 skyblue-->
<ul>
<li class="li-class">li 1번</li>
<!--ul>li.li-class : 10점
ul : 1점
ul>li : 2점
이기때문에 salmon-->
</ul>
</body>
열심히 공부하고 있지만, 오류 사항이 존재 할 수 있습니다.
수정 사항이 존재 할 경우 알려주시면 감사하겠습니다 <(__)>
728x90
반응형