[CSS] selector

yihyun·2024년 8월 21일

Front-end

목록 보기
3/22

selector

css selector 는 css를 적용하기 위한 특정 태그(요소)를 가져오는데 도움을 준다.

간단하게 원하는 요소를 가져올 수 있어서 많이 사용되고, 성능이 좋다는 특징이 있다.

selector은 head에 위치해야 하며 <style> 태그로 감싸 사용해야 한다.

selector 방법 3가지
#id : 아이디가 id인 요소 (하나만 인정되며 중복될 경우 맨 위에 있는 것만 적용됨)

  • # id 의 경우 중복 사용이 불가능하며, 중복해서 사용할 경우 가장 위에 있는 id만 적용된다.
  • body 태그에 id = "아이디 이름" 을 작성해준다.

.class : 클래스가 class인 요소 (중복 허용 가능)

  • . class 의 경우 중복 사용이 가능하다.
  • body 태그에 class = "클래스이름" 을 작성해준다.

p : p 요소

  • 사용한 요소 전체에 적용할 때 사용하며 haed에 요소명을 입력해서 사용한다.
  • 중복 사용할 경우 , 로 요소를 구분해준다.
  • 요소에 해당하는 특정 속성에만 지정할 경우 태그[속성]{} 을 작성해준다.
  • 어떤 요소의 특정 자식만 선택할 경우 부모 > 자식으로 입력 가능한데 >는 생략 가능하다.
  • 특정 단어를 검색하고 싶을 경우 ~= 를 사용해줄 수 있다. ex) img[alt="hi"]
<html>
    <head>
        <meta charset="UTF-8">
        <title>CSS TUTORIALS</title>
        <link rel="icon" href="../img/chrome.png">
        <style>
            p{
                /*모든 p 태그에 background-color 설정*/
                background-color: darkslateblue;
                color: whitesmoke;
            }
            .myclass{
                /*class가 myclass인 요소의 글자 색상 설정*/
                color: plum;
            }
            p, div{
                /*p와 div태그 요소들을 가져와 글자 굵기를 설정*/  
                font-weight: 600; 
            }
            div>p{ /* > 는 생략 가능하다. (ex. div p)*/
                /*div 자식인 p태그 요소를 가져와 배경색 설정*/
                background-color: deeppink;
            }
            /*속성으로 가져오기*/
            input[type="text"]{
                /*input 태그 중 type이라는 속성이 text인 요소*/
                background-color: rgb(240, 201, 222);
            }
            input[type="email"]{
                background-color: rgb(186, 209, 243);
            }
            img{
                width: 100px;
            }
            img[alt~="버섯"]{ /* ~= 단어를 포함하고 있으면*/
                border: 1px solid rgb(202, 16, 156);
            }
            img:hover{
                border: 2px solid rgb(100, 3, 100);
            }

            a{
                text-decoration-color: palevioletred;
                text-decoration-style: double;
            }
            /*hover : 마우스가 오버되면 */
            a:hover{
                background-color: rgb(231, 196, 228);
            }
            #myid{
                color: rgb(236, 99, 172);
                font-size: 20px;
            }
        </style>
    </head>
    <body>
        <p id="myid">id가 있는 요소</p>
        <p class="myclass">class가 있는 요소</p>
        <p class="myclass">class가 있는 요소</p>
        <p>태그만 있는 요소</p>
        <div>div 요소</div>
        <div>
            <p>div안에 있는 p태그</p>
        </div>
        <input type="text"/>
        <input type="email"/>
        <br/><br/>
        <img src="../img/img01.jpg" alt="초록 버섯"/>
        <img src="../img/img02.jpg" alt=""/>
        <img src="../img/img03.jpg" alt="마리오"/>
        <img src="../img/img04.jpg" alt="노란 버섯"/>
        <br/><br/>
        <a href="#">테스트 링크</a>
    </body>
</html>

profile
개발자가 되어보자

0개의 댓글