[CSS] 가상 선택자, 복합 선택자, 속성 선택자

Jungwook·2023년 5월 8일
0

HTML / CSS

목록 보기
12/18

가상 클래스 선택자

선택자 뒤에 :가상이벤트를 붙이면 특정 이벤트마다 적용 할 스타일을 설정 할 수 있으며, 이를 가상 (추상)클래스라 한다.

hover : 선택자에 마우스 포인터가 올라가 있는 동안에만! 선택된다.

 a:hover {
            color: yellowgreen;
            font-weight: bold;
            font-size: 20px;
        }

active: 선택자를 마우스로 누르고 있는 동안에만 선택된다.

 .box2 {
            width: 100px;
            height: 100px;
            background-color: pink;
            transition-duration: 1s;
        }

        .box2:active {
            width: 200px;
            background-color: skyblue;
        }

focus: 포거스가 된 동안에만 선택된다.
ex) 대화형 컨텐츠(input, img)에서 사용이 가능하다.

input {
           width: 100px;
           background-color: hotpink;
           outline: none;
           /*input의 외곽선을 설정*/
           border: 3px solid red;
           padding: 5px 10px;
           transition-duration: 1s;
       }
       input:focus {
           width: 200px;
           background-color: yellow;
           border: 5px solid blue;
       }

html 계층 구조에서 특정 위치에 있는 요소를 수학적으로 접근
first - child: 선택자가 형제 요소 중 첫번째 요소라면 선택
last- child 선택자 중에서 마지막 요소라면 선택

.fruits>li:first-child {
            color: red;
        }
.fruits > li:last-child{
            color: violet;
        }

전체 코드

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>가상 선택자1</title>
    <style>
        /* 
가상 클래스 선택자 
선택자 뒤에 :가상이벤트를 붙이면 특정 이벤트마다 적용 할 스타일을 설정 할 수 있으며, 
이를 가상 (추상)클래스라 한다. 

    : 이 가상 클래스 선택자이다.
*/


        /*px폰트를 고정해서 사용할 때*/
        a:hover {
            color: yellowgreen;
            font-weight: bold;
            font-size: 20px;
        }
        
        /*hover : 선택자에 마우스 포인터가 올라가 있는 동안에만! 선택된다. */
        .box1 {
            width: 100px;
            height: 100px;
            background-color: tomato;
            transition-duration: 1s;
            /*애니메이션 실행시간, 단위는 초 단위로 뒤에 s*/
        }

        .box1:hover {
            width: 200px;
            background-color: blue;
        }
        
        /*active: 선택자를 마우스로 누르고 있는 동안에만 선택된다.*/
        .box2 {
            width: 100px;
            height: 100px;
            background-color: pink;
            transition-duration: 1s;
        }

        .box2:active {
            width: 200px;
            background-color: skyblue;
        }
        
        
        
                /*focus: 포거스가 된 동안에만 선택된다.
                ex) 대화형 컨텐츠(input, img)에서 사용이 가능하다. 
                */
        input {
            width: 100px;
            background-color: hotpink;
            outline: none;
            /*input의 외곽선을 설정*/
            border: 3px solid red;
            padding: 5px 10px;
            transition-duration: 1s;
        }
        input:focus {
            width: 200px;
            background-color: yellow;
            border: 5px solid blue;
        }


        /*html 계층 구조에서 특정 위치에 있는 요소를 수학적으로 접근 */
        /*first - child: 선택자가 형제 요소 중 첫번째 요소라면 선택 */

        .fruits>li:first-child {
            color: red;
        }

        /*last- child 선택자 중에서 마지막 요소라면 선택*/
        .fruits > li:last-child{
            color: violet;
        }

    </style>




</head>

<body>
    <a href="https://www.google.com">google</a>
    <div class="box1"></div>
    <div class="box2"></div>
    <input type="text" />

    <ul class="fruits">
        <li>딸기</li> <!--first child-->
        <li>사과</li>
        <li>오렌지</li>
        <li>망고</li> <!--last child-->
    </ul>


</body>

</html>

가상 클래스 선택자2

  • nth-child: 선택자 형제 요소 중에서 n번째 요소라면 선택!
    인덱스는 nth-child(index) 지정
    인덱스 1부터 시작딘다.
 .fruits1 li:nth-child(2){     /*class="fruits1"의 nth-child(2)인 사과 선택*/
            color: red;
        }

연산
()안에 n을 사용하면 0부터 시작해서 1씩 증가된다.
n을 이용한 곱셈 연산시 *사용안한다. n앞에 숫자를 적용한다.
n을 이용한 덧셈, 뺄셈 연산 시 사용가능하다.
-n +5 앞에서 부터 5개만 선택!

 .fruits2 li:nth-child(2n){  /*짝수 번째 모든 요소를 선택한다.*/  
            color: brown;
        }
 

        .fruits2 li:nth-child(2n+1){  /*홀수 번째 모든 요소를 선택한다.*/  
            color: aqua;
        }

        
        .fruits3 li:nth-child(n+3){ /*3번째 이후 모든 요소를 선택한다.*/
            color: hotpink;
        }

       .fruits4 p:nth-child(2){  /*.fruits4의 p태그 중에서 첫번째를 선택*/
        color: red;
       }

       .fruits4 p:nth-child(3){ /*.fruits4의 p태그 중에서 두번째를 선택*/
        color: orange;
       }

전체 코드

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>가상선택자2</title>
    <style>

        /*nth-child: 선택자 형제 요소 중에서 n번째 요소라면 선택! 
        인덱스는 nth-child(index) 지정
        인덱스 1부터 시작딘다.
        */
        .fruits1 li:nth-child(2){     /*class="fruits1"의 nth-child(2)인 사과 선택*/
            color: red;
        }

        /*연산
        ()안에 n을 사용하면 0부터 시작해서 1씩 증가된다.
        n을 이용한 곱셈 연산시 *사용안한다. n앞에 숫자를 적용한다.
        n을 이용한 덧셈, 뺄셈 연산 시 사용가능하다. 
          -n +5 앞에서 부터 5개만 선택!
        */

        .fruits2 li:nth-child(2n){  /*짝수 번째 모든 요소를 선택한다.*/  
            color: brown;
        }
 

        .fruits2 li:nth-child(2n+1){  /*홀수 번째 모든 요소를 선택한다.*/  
            color: aqua;
        }

        
        .fruits3 li:nth-child(n+3){ /*3번째 이후 모든 요소를 선택한다.*/
            color: hotpink;
        }

       .fruits4 p:nth-child(2){  /*.fruits4의 p태그 중에서 첫번째를 선택*/
        color: red;
       }

       .fruits4 p:nth-child(3){ /*.fruits4의 p태그 중에서 두번째를 선택*/
        color: orange;
       }




    </style>

</head>
<body>
    <ul class="fruits1">
		<li>딸기</li>
		<li>사과</li> <!-- nth-child(2) -->
		<li>오렌지</li>
		<li>망고</li>
	</ul>
	<hr/>

	<ul class="fruits2">
		<li>딸기</li> <!-- nth-child(2n) -->
		<li>사과</li> <!-- nth-child(2n + 1) -->
		<li>오렌지</li> <!-- nth-child(2n) -->
		<li>망고</li> <!-- nth-child(2n + 1) -->
	</ul>
	<hr/>

	<ul class="fruits3">
		<li>딸기</li>
		<li>사과</li>
		<li>오렌지</li> <!-- nth-child(n + 3) -->
		<li>망고</li> <!-- nth-child(n + 3) -->
	</ul>
	<hr/>

	<ul class="fruits4">
		<div>딸기</div>
		<p>사과</p>
		<p>오렌지</p>
		<span>망고</span>
	</ul>
	<hr/>

	<div class="box-group">
		<div>1</div>
		<div>2</div>
		<div>3
			<p>3-1</p>
			<div>3-2</div>
			<div>3-3</div>
		</div>
	</div>




</body>
</html>

실행 결과

가상 클래스 선택자3

nth-of-type(): 지정된 태그와 동일 타입(태그)의 형제 요소 중 n번째 요소라면 선택한다.

.fruits1 p:nth-of-type(1) {
		color: blue;
	}

nth-of-type()은 태그와 함께 사용해야하므로 class와 함께 사용하면 동작되지 않는다.

.fruits2 .red:nth-of-type(1) { /* 동작되지 않는다. */
		color: lime;
	}
	/* 사과만 선택하려면 위의 방식대신 아래와 같이 해야한다. */
	.fruits2 li:nth-of-type(2) {
		color: yellowgreen;
	}

not: 부정 연산자로 ()안에 지정된 요소가 아닌 요소를 선택한다.

.fruits3 li.apple {
		color: hotpink;
	}
	.fruits3 li:not(.apple) {
		color: green;
	}

전체 코드

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>가상 클래스 선택자</title>

<style type="text/css">
	
	/* nth-of-type(): 지정된 태그와 동일 타입(태그)의 형제 요소 중 n번째 요소라면 선택한다. */
	.fruits1 p:nth-of-type(1) {
		color: blue;
	}

	/* nth-of-type()은 태그와 함께 사용해야하므로 class와 함께 사용하면 동작되지 않는다. */
	.fruits2 .red:nth-of-type(1) { /* 동작되지 않는다. */
		color: lime;
	}
	/* 사과만 선택하려면 위의 방식대신 아래와 같이 해야한다. */
	.fruits2 li:nth-of-type(2) {
		color: yellowgreen;
	}
	
	/* not: 부정 연산자로 ()안에 지정된 요소가 아닌 요소를 선택한다. */
	.fruits3 li.apple {
		color: hotpink;
	}
	.fruits3 li:not(.apple) {
		color: green;
	}
	
</style>

</head>
<body>

	<ul class="fruits1">
		<div>딸기</div>
		<p>사과</p>
		<p>오렌지</p>
		<span>망고</span>
	</ul>
	<hr/>

	<ul class="fruits2">
		<li>딸기</li>
		<li class="red">사과</li>
		<li>오렌지</li>
		<li class="red">망고</li>
	</ul>
	<hr/>
	
	<ul class="fruits3">
		<li>딸기</li>
		<li class="apple">사과</li>
		<li>오렌지</li>
		<li>망고</li>
	</ul>
	<hr/>
	
</body>
</html>

실행 결과

복합 선택자

기본 선택자를 붙여서 만든 선택자를 복합 선택자라 한다.

자식 선택자 : > 이 선택자 이다. 자식요소(한 단계 아래 요소를 선택한다.)
첫 번째 요소의 바로 아래 자식인 노드를 선택

  ul > .orange{
            color: blue;
        }

자손 선택자 : " " (공백 1칸)
자손 요소(모든 요소)를 선택한다.
""(공백) 결합자는 첫 번째 요소의 자손인 노드를 선택

 div .apple{
            color: purple;
        }

인접 형제 선택자: + 다음 형제 요소 1개를 선택한다.
+ 결합자는 인접 형제, 즉 첫 번째 요소의 바로 뒤에 위치하면서 같은 부모를 공유하는 두 번째 요소를 선택

.apple + li {
            color: aqua;
        }

일반 형제 선택자 : ~가 선택자 이다
다음 형제 요소 모두를 선택한다.
첫 번째 요소를 뒤따르면서 같은 부모를 공유하는 두 번째 요소를 선택

 .orange ~ li{
            text-decoration: underline;
        }

전체 코드

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>복합선택자</title>
    <style>
        /*기본 선택자를 붙여서 만든 선택자를 복합 선택자라 한다. */
        
        /*span 태그 중에서 class 속성이 orange 요소 선택!*/
        span.orange{
            color : red;
        }

        /*자식 선택자 : ">" 이 선택자 이다. 자식요소(한 단계 아래 요소를 선택한다.) 
        첫 번째 요소의 바로 아래 자식인 노드를 선택*/
        ul > .orange{
            color: blue;
        }

        /*자손 선택자 : " " (공백 1칸) */
        /*자손 요소(모든 요소)를 선택한다.
        ""(공백) 결합자는 첫 번째 요소의 자손인 노드를 선택합니다. */
        div .apple{
            color: purple;
        }

        /*인접 형제 선택자: `+` 다음 형제 요소 1개를 선택한다. 
        `+` 결합자는 인접 형제, 즉 첫 번째 요소의 바로 뒤에 위치하면서 같은 부모를 공유하는 두 번째 요소를 선택*/
        .apple + li {
            color: aqua;
        }

        /*일반 형제 선택자 : `~`가 선택자 이다
        다음 형제 요소 모두를 선택한다.
        첫 번째 요소를 뒤따르면서 같은 부모를 공유하는 두 번째 요소를 선택*/
        .orange ~ li{
            text-decoration: underline;
        }



    </style>
</head>

<body>

    <div>
        <ul>
            <li class="apple">사과</li>
            <li>딸기</li>
            <li class="orange">오렌지</li>
        </ul>
        <div class="apple">당근
            <p>토마토</p>
            <span class="orange">멜론</span>
        </div>
        <ul>
            <li>딸기</li>
            <li>수박</li>
            <li class="orange">오렌지</li>
            <li>망고</li>
            <li>사과</li>
        </ul>
    </div>

</body>

</html>

실행 결과

속성 선택자

태그 내에 특정 속성에 값을 가지고 있는 html 요소를 선택한다.
[속성이름]: []안에 지정한 속성이 설정된 요소를 선택한다.

[disabled]{
    opacity: 0.2;  /*투명도: 기본값은 1, 숫자를 0으로 보낼 수록 투명해진다.*/
}

[속성이름="속성값"]: []안에 지정된 속성과 속성값이 일치하는 요소를 선택한다.

[type="password"]{
    font-weight: bold;
    border-radius: 5px;
}

[속성이름 ^="속성값"] : 속성값으로 시작하는 요소를 선택한다.

[class ^="btn"]{
    font-weight: bold;
    border-radius: 5px;
}

[속성이름 $="속성값"] : 속성값으로 끝나는 요소를 선택한다.

[class$="success"]{
    color: orange;
}
[class$="danger"]{
    color: hotpink;
}

전체 코드

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>속성 선택자</title>

    <style>
/*
속성선택자
태그 내에 특정 속성에 값을 가지고 있는 html 요소를 선택한다.
[속성이름]: []안에 지정한 속성이 설정된 요소를 선택한다.
*/
[disabled]{
    opacity: 0.2;  /*투명도: 기본값은 1, 숫자를 0으로 보낼 수록 투명해진다.*/
}
/*[속성이름="속성값"]: []안에 지정된 속성과 속성값이 일치하는 요소를 선택한다.*/
[type="password"]{
    font-weight: bold;
    border-radius: 5px;
}

/*[속성이름 ^="속성값"] : 속성값으로 시작하는 요소를 선택한다. */
[class ^="btn"]{
    font-weight: bold;
    border-radius: 5px;
}

/*[속성이름 $="속성값"] : 속성값으로 끝나는 요소를 선택한다.*/
[class$="success"]{
    color: orange;
}
[class$="danger"]{
    color: hotpink;
}

    </style>

</head>
<body>
    <input type="text" value="홍길동"/>
    <input type="password" value="1234"/>
    <input type="text" value="disabled 텍스트" disabled="disabled"/>

<br><br>

<button class="btn-success" type="button">Success</button>
<button class="btn-danger" type="button">Danger</button>
<button class="button">Normal</button>


    
</body>
</html>

실행 결과

0개의 댓글

관련 채용 정보