본문 바로가기

WEB

CSS올바른 사용법, CSS-ID 선택자, CSS 우선순위

아이디나 클래스는 (내부스타일・외부스타일) CSS 방식에서 사용.

 

id, class 예제 

<style>
#dt {text-decoration:underline; color:green;}
.dt {text-decoration:none; color:green;}
#dt .site {color:red;}
#dt .host {color:blue;}
.site {color:yellow}
.host {color:yellow}
</style>

<div id="dt" class='dt'>
  <p class='site'>홈페이지</p>
  <p class='host'>tistory.com</p>
</div>

 

id, class 선택자 기호  

 

# (샾)으로 선언한 스타일 : id (아이디) 속성으로 연결.

. (마침표)로 선언한 스타일 : class (클래스) 속성으로 연결.

 

※ 선택자 (Selector) : 스타일적용영역을 선택하는 것을 말함. 

 

 

id, class 선택자 우선순위   

# (아이디)는 . (클래스)보다 상위 선택자임.

즉, 동일요소에 대한 스타일이 class와 id 중복 정의된 경우, id 스타일이 우선 적용됨.

 

선택자 적용 우선 순위 (= 선택자 명시도 = 선택자 중요도)

id  >  class  >  요소
(우선 순위 :아이디 > 클래스 > 요소) 적용되는 예제.

<style>

#id {color:green;}

.class {color:blue;}

div {color:red;}
</style>

 

<div id='id' class='class'>

  IT랑 (itlang.tistory.com)

</div>



(우선 순위: 인라인 스타일 > 아이디 > 클래스 > 요소) 적용 예제.


<style>

#id {color:green;}

.class {color:blue;}

div {color:red;}

</style>



<div id='id' class='class' style='color:magenta'>

  IT랑 (itlang.tistory.com)

</div>



인라인스타일 방식 경우, 위치 상관없이 우선적용.

 

<style>

#id {color:green;}

.class {color:blue;}

div {color:red;}

</style>



<div style='color:magenta' id='id' class='class' >

 IT랑 (itlang.tistory.com)

</div>


※ 위쪽에 있는 선택자일수록 명시도가 높아 우선 적용되는 예제.

 

<style>

h1#it {color:gray;}

#it {color:magenta;}

h1.it {color:green;}

.it {color:red;}

h1 {color:blue;}

body {color:tomato;}

</style>

 

<h1 id='it' class="it"> IT랑 (itlang.tistory.com)</h1>

 

id・class 선택자 바른 사용법

예제1)

<style>

#title{color:red; font-size: 20pt;}

#content{color:blue; font-size: 11pt;}

</style>



<p id="title">글 제목</p>
<p id="content">여기는 글 내용입니다.</p>

 

위 처럼, id만을 이용해 표현할 수도 있음. 
다만, 관리적인 측면에서 id는 스타일 영역 지정할 때 한번만 사용하는 게 좋은 점에서, 
위처럼 줄 마다 다른 id로 표현하는 건 좋지 않음.

첫 번째 상자 예처럼, css가 적용될 영역을 id로 지정 후, 그 영역 내 구체적인 스타일은 class를 이용 권장.

 

 

예제2)

<style>
.title {color:red; font-size: 20pt;}
.content {color:blue; font-size: 11pt;}
</style>

<p class="title">글 제목</p>
<p class="content">여기는 글 내용입니다.</p>

또, 위처럼 id없이 class만을 이용해 표현도 가능한데, 이 역시 바람직하지 않음.

id없이 class만 이용해 선언 시, 
다른 영역의 같은 class에 영향을 미칠 수도, 또 영향을 받을 수도 있기 때문임.
정렬이 틀어지는 원인 중 가장 흔한 경우 임..

 

 

해당영역 ID 및 class를 함께 혼용해서 사용하는것을 추천.