-
CSS Selectorweb/css 2023. 12. 21. 20:24
개요
css style 파일 등의 정의 패턴을 보면 아래와 같다.
selector { property: value; }
여기서 selector 값의 다양한 형태를 배워보자.
전체 선택
* { background-color: cyan; }
Element 선택
h2 { color: crimson; }
Element 다중 선택
h1, h2 { color: crimson; }
ID 선택
#my-id { background-color: coral; }
class 선택
.my-class { background-color: coral; }
자손(descendant) 선택
ul a { color: red; }
ul 에 바로 이어 나오는 anchor 뿐만 아니라, 아래와 같은 anchor 도 선택된다. (ul 하위의 모든 anchor 가 선택됨)
<ul> <li class="done"><a href="#">descendant</a></li> </ul>
인접(adjacent) 선택
아래는 h1 다음에 오는 동일 레벨의 p 태그를 선택함. (부모-자식 관계가 아닌)
h1 + p { color: red; }
아래 예제에서 Selected 가 선택된다.
<h1>Todos</h1> <p>Selected</p>
직계 자손(direct child) 선택
아래는 div 다음에 오는 직계 자손의 li 만을 선택함.
ul > li { color: red; }
속성(attribute) 선택
input[type="text"] { width: 300px; }
특성 class 속성인 element 를 선택할 때 아래 처럼 할 수도 있지만 ...
section[class="post"] { color: red; }
이것 보다는 아래처럼 하는 것이 좋다. (이건 좀 특이한 것 같다.)
section.post { color: red; }
속성 값의 부분 매치로 *= 를 사용도 가능하다. (anchor tag 중 href 에 google 이 들어간 것)
a[href*="google"] { color: red; }
유사 클래스 (pseudo class)
유사 클래스 선택자는 ':' 으로 시작한다.
a:hover { color: red; }
위의 예는 anchor hover 시 색상을 변경한다.
:hover 말고도 :checked, :first, :first-child, :not(), :nth-child(), :nth-of-type() 등이 있다.
:nth-of-type(3) 은 3번째만 선택하지만 :nth-of-type(3n) 은 3의 배수의 element 를 모두 선택한다.
유사 요소 (pseudo element)
h2::first-letter { font-size:50px; }
위의 예제는 h2 의 맨 첫 글자를 선택한다.
::first-line, ::selection (마우스 드래그로 선택한 영역) 등이 있다.
연습
foo#bar.qux
<foo id="bar" class="qux" />
foo #bar .qux
<foo> <span> <div id="bar"> <div class="qux"></div> </div> </span> </foo>
foo > #bar > .qux
<foo> <div id="bar"> <div class="qux"></div> </div> </foo>
.three.four
<h1 class="three four">Double Class</h1>
'web > css' 카테고리의 다른 글
위치 속성 (position) (0) 2024.01.01 CSS 단위 (0) 2023.12.31 CSS 박스 모델 (0) 2023.12.29 색, 텍스트, 글꼴 (0) 2023.12.21