p:first-child {color:red;}
-> p요소 중에서 첫번째 자식을 선택
p:last-child {color:blue;}
-> p요소 중에서 마지막 자식을 선택
n은 0부터 시작하는 정수이다.
<style>
/* ol 요소의 자식 요소인 li 요소 중에서 짝수번째 요소만을 선택 */
ol > li:nth-child(2n) { color: orange; }
/* ol 요소의 자식 요소인 li 요소 중에서 홀수번째 요소만을 선택 */
ol > li:nth-child(2n+1) { color: green; }
/* ol 요소의 자식 요소인 li 요소 중에서 첫번쨰 요소만을 선택 */
ol > li:first-child { color: red; }
/* ol 요소의 자식 요소인 li 요소 중에서 마지막 요소만을 선택 */
ol > li:last-child { color: blue; }
/* ol 요소의 자식 요소인 li 요소 중에서 4번째 요소 요소만을 선택 */
ol > li:nth-child(4) { background: brown; }
/* ul 요소의 모든 자식 요소 중에서 뒤에서부터 시작하여 홀수번째 요소만을 선택 */
ul > :nth-last-child(2n+1) { color: red; }
/* ul 요소의 모든 자식 요소 중에서 뒤에서부터 시작하여 짝수번째 요소만을 선택 */
ul > :nth-last-child(2n) { color: blue; }
</style>
<!DOCTYPE html>
<html>
<head>
<style>
/* p 요소의 부모 요소의 자식 요소 중 첫번째 등장하는 p 요소 */
p:first-of-type { color: red; }
/* p 요소의 부모 요소의 자식 요소 중 마지막 등장하는 p 요소 */
p:last-of-type { color: blue; }
/* p 요소의 부모 요소의 자식 요소 중 앞에서 2번째에 등장하는 p 요소 */
p:nth-of-type(2) { color: green; }
/* p 요소의 부모 요소의 자식 요소 중 뒤에서 2번째에 등장하는 p 요소 */
p:nth-last-of-type(2) { color: orange;}
/* p 요소 중에서 첫번째 자식을 선택 */
p:first-child { background: brown;}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
<div>
<h1>This is a heading</h1>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
</div>
</body>
</html>
input:not([type=password]) {
background: yellow;
}
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0;
}
div {
float: left;
width: 32%;
height: 200px;
background-color: red;
/* margin-bottom: 2%; */
color: #fff;
font-size: 3em;
line-height: 200px;
text-align: center;
}
/* div 요소 중에서 1, 4, 7...번째 등장하는 요소가 아닌 요소만을 선택 */
/* 1, 4, 7... : 공차가 3인 등차수열 */
div:not(:nth-of-type(3n+1)) {
margin-left: 2%;
}
/* div 요소 중에서 4번째 이후 등장하는 요소가 아닌 요소만을 선택 */
div:not(:nth-of-type(n+4)) {
margin-bottom: 2%;
}
</style>
</head>
<body>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</body>
</html>
input[type="text"]:valid {
background-color: greenyellow;
}
input[type="text"]:invalid {
background-color: red;
}
가상 요소는 요소의 특정 부분에 스타일을 적용하기 위해 사용된다. 특정 부분이란
요소 콘텐츠의 첫글자 또는 첫줄
요소 콘텐츠의 앞 또는 뒤
가상 요소에는 두개의 콜론(::)을 사용한다.CSS 표준에 의해 미리 정의된 이름이 있기 때문에 임의의 이름을 사용할 수 없다.
selector::pseudo-element {
property:value;
}
/* p 요소 콘텐츠의 첫글자를 선택 */
p::first-letter { font-size: 3em; }
/* p 요소 콘텐츠의 첫줄을 선택 */
p::first-line { color: red; }
/* h1 요소 콘텐츠의 앞 공간에 content 어트리뷰트 값을 삽입한다 */
h1::before {
content: " HTML!!! ";
color: blue;
}
/* h1 요소 콘텐츠의 뒷 공간에 content 어트리뷰트 값을 삽입한다 */
h1::after {
content: " CSS3!!!";
color: red;
}
/* 드래그한 콘텐츠를 선택한다 */
::selection {
color: red;
background: yellow;
}