[카카오톡 클론코딩] # 3.14 Pseudo Selectors part One

Gata·2023년 8월 8일
0

Pseudo Selector(가상 선택자)

  • 보통 선택자는 HTML 태그, class, id등 HTML 요소(element)를 직접적으로 선택하여 CSS를 통해 꾸며준다. 하지만, Pseudo Selector를 이용하면 HTML를 수정할 필요 없이 CSS에서만 선택하면 돼서 복잡한 과정을 간단히 할 수 있다.

div:first-child/last-child

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body{
            height: 1000vh;
            margin: 50px;
        }
        div{
            width: 150px;
            height: 150px;
            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>


첫번째 div는 tomato색으로, 마지막 div는 teal색으로 변했다. class나 id를 사용하지 않고 div:first-class, div:last-class를 이용하는 것이 훨씬 좋은 방법이다.

span:nth-child()

  • span:nth-child()의 괄호안에 몇번째 span을 의미하는지 숫자를 넣으면 된다.
  • 괄호에 숫자 대신 even 혹은 odd로 짝수와 홀수번째 span을 가리킬 수 있다.
  • 괄호에 n+1, 2n+1, 3n+1, 4n+1, 5n+1을 쓸 수도 있다.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body{
            height: 1000vh;
            margin: 50px;
        }
        span{
            background-color: violet;
        }
        span:nth-child(2),
        span:nth-child(4){
            background-color: yellow;
        }

    </style>
</head>
<body>
  <span>hello</span>
  <span>hello</span>
  <span>hello</span>
  <span>hello</span>
  <span>hello</span>
  <span>hello</span>
  <span>hello</span>
</body>
</html>

span:nth-child(even)

  • 짝수 번째를 한꺼번에 바꿀 수 있다.
    (주의❗:과 nth을 붙여써야 된다!)

    2,4,6번째, 즉 짝수 번째 span이 노란색으로 변한다.

span:nth-child(odd)

  • 홀수 번째를 한꺼번에 바꿀 수 있다. 1,3,5번째, 즉 홀수 번째 span이 노란색으로 변한다.

span:nth-child(n+1/2n+1/3n+1/4n+1/5n+1....)

  • 예를 들어 아래와 같은 경우 4배수 마다 노란색이 적용된다.
span:nth-child(4n+1){
	 background-color: yellow;
}

profile
개발은 즐거워🪇

0개의 댓글

관련 채용 정보