2. CSS

CSS pseudo selectors / first-child & last-child

도피디 2024. 11. 27. 23:46
반응형

pseudo selectors: 좀 더 세부적으로 엘리먼트를 선택해 주는 것!

 

 

 

기본 코딩

<!DOCTYPE html>
<html lang="kr">
<head>
<title>The Nick Times</title>
<style>
body {
height: 1000vh;
margin: 50px;
}
div {
width: 300px;
height: 300px;
background-color: wheat;
position: relative;
}
</style>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>

 

 

 

 

결과

 


 

pseudo selectors 사용하기 (first-child & last-child)

<!DOCTYPE html>
<html lang="kr">
<head>
<title>The Nick Times</title>
<style>
body {
height: 1000vh;
margin: 50px;
}
div {
width: 300px;
height: 300px;
background-color: wheat;
position: relative;
}
div:last-child {
background-color: teal;
}
</style>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>

 

last-child는 리스트에 있는 div들 중

마지막에 있는 걸 뜻한다. 

 

 

 

 

결과

 

오오 가장 마지막 div가 초록색으로 바뀌었다!

 


 

 

첫 번째 자식도 선택할 수 있음!

<!DOCTYPE html>
<html lang="kr">
<head>
<title>The Nick Times</title>
<style>
body {
height: 1000vh;
margin: 50px;
}
div {
width: 300px;
height: 300px;
background-color: wheat;
position: relative;
}
div:first-child {
background-color: tomato;
}
div:last-child {
background-color: teal;
}
</style>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>

 

 

 

 

결과

 


이렇게

first-child 이나 last-child 을 쓰는게

class나 id를 만드는 것보다 훨씬 좋은 방법이다.

반응형