CSS는 HTML을 꾸미기 위해서 사용한다.
HTML을 꾸미려면 특정 엘리먼트를 선택해야 하는데 이때 사용하는게 CSS 선택자이다.
CSS 선택자는 크게 5종류로 나눌 수 있다.
기본 선택자
*
element
.(class)
#(id)
[attr](특성)
<div>Hello</div>
<div class="header"></div>
<div id="footer"></div>
<input type="radio" />
* { background: red; } /* 전체 선택 */
div { height: 300px; } /* div 요소 전체 선택 */
.header { width: 100px; } /* header라는 class를 가진 요소 선택 */
#footer { margin: 0 auto; } /* footer라는 id를 가진 요소 선택 */
input[type="radio"] { display: none; }
/* input 요소 중 type 속성을 가지고 속성값이 radio인 것 선택 */
그룹 선택자
,
<ul>
<li>Hello</li>
</ul>
ul, li { list-style: none; } /* ul 요소와 li 요소 선택 */
결합자
(자손결합자)
>(자식 결합자)
~(일반 형제 결합자)
+(인접 형제 결합자)
<ul>
<li>Say</li>
<li><span class="content">Hello</span><li>
<li><a class="content" href="#">Link</a></li>
</ul>
<div class="bro">brother</div>
<div class="near">near</div>
/* 자손 결합자 */
ul .content { color: red; } /* ul 안에 있는 content라는 클래스를 가진 요소 선택 */
/* 자식 결합자 */
ul > li { color: green; } /* ul 안에 있는 li 요소 전체 선택 */
/* 일반 형제 결합자 */
ul ~ .near { color: blue; } /* ul과 형제 관계인 near라는 클래스를 가진 요소 선택 */
/* 인접 형제 결합자 */
ul + .bro { color: gray; } /* ul과 인접한 형제인 bro라는 클래스를 가진 요소 선택 */
가상 클래스 선택자
:hover
:focus
:checked
first-child
nth-child
:last-child
<input type="text" id="text_box" />
<label for="text_box">text_box</label>
<input type="checkbox" id="check_box" />
<label for="check_box">
<span></span>
<span></span>
<span></span>
</label>
<div>
<ul>
<li>menu1</li>
<li>menu2</li>
<li>menu3</li>
</ul>
</div>
div > ul > li:hover {
cursor: pointer;
}
/* menu에 마우스를 올리면 커서가 바뀜 */
#text_box:focus + label {
color: red;
}
/* text를 입력할 수 있는 input box를 선택하면 text_box 텍스트가 빨간색으로 변함 */
#check_box:checked + label {
color: blue;
}
/* 체크박스를 선택하면 1 2 3 텍스트가 파란색으로 변함 */
#check_box + label > span:first-child {
color: green;
}
/* label의 자식 요소중 첫 번째인 요소인 1이 녹색으로 변함 */
#check_box + label > span:nth-child(2) {
color: blue;
}
/* label의 자식 요소중 두 번째 요소인 2가 파란색으로 변함 */
#check_box + label > span:last-child {
color: red;
}
/* label의 자식 요소중 마지막 요소인 3이 빨간색으로 변함 */
가상 요소 선택자
css에서 유일하게 html을 만들 수 있음
가상으로 span이 만들어 졌다고 볼 수 있음::before
: 선택 영역 앞::after
: 선택 영역 뒤
<div id="before">Before</div>
<div id="after">After</div>
#before::before {
content: "-"
}
/* Before 글자 앞에 -가 생김 */
#after::after {
content: "*"
}
/* After 글자 뒤에 *이 생김 */
'HTML/CSS' 카테고리의 다른 글
[HTML/CSS] HTML 핵심 개념 (0) | 2022.10.27 |
---|---|
[HTML] label 요소 (0) | 2022.10.26 |
[CSS] CSS 적용하는 3가지 방법 (0) | 2022.10.21 |