[웹 서비스 개발] HTML_CSS_class_id_24_posted

김광일·2024년 11월 15일

웹 서비스 개발

목록 보기
24/45

일자 : 9주차 2차시

Class & ID Selector

[1] ID Selector

  • 태그 내에서는 id = "id명" 속성을 지정한다.
  • 스타일 내에서는 #을 참고하여 접근한다.
  • 하나의 id 스타일로 고유한 태그에만 지정할 수 있다.

1) 예시

<html>
  <head>
    <style>      
      #special{
		background-color : yellow;
      	color : red;
      }
    </style>
  </head>
  <body>
    <p id = "special">id selector</p>
  </body>
</html>

[2] Class Selector

  • 태그 내에서는 class = "class명" 속성을 지정한다.
  • 스타일 내에서는 .을 참고하여 접근한다.
  • 하나의 class 스타일로 여러 개의 태그에 지정할 수 있다.

1) 예시

<html>
  <head>
    <style>      
      .special{
		background-color : yellow;
      	color : red;
      }
    </style>
  </head>
  <body>
    <p class = "special">class selector</p>
    <h1 class = "special">class selector</h1>
  </body>
</html>

[3]element와 함께 사용하기

  • 태그에 바로 #id명 또는 .class명을 작성하여 접근한다.
<html>
  <head>
    <style>      
      p#special{
		background-color : yellow;
      	color : red;
      }
      h2#special{
		background-color : yellow;
      	color : blue;
      }
    </style>
  </head>
  <body>
    <p id = "special">id selector</p>
    <h2 id = "special">id selector</h2>
  </body>
</html>

[4] selector group

  • 콤마(,)을 사용하여 연결하여 동일 스타일을 지정한다.
<html>
  <head>
    <style>      
      p, h2{
		background-color : yellow;
      	color : red;
      }
    </style>
  </head>
  <body>
    <p>id selector</p>
    <h2>id selector</h2>
  </body>
</html>
  • a 태그의 href에 #id명을 삽입하여 '북마크' 기능처럼 사용할 수 있다.
<html>

<body>
    <p><a href="#C4">Jump to Chapter 4</a></p>

    <h2>Chapter 1</h2>
    <p>This chapter explains ba bla bla</p>

    <h2>Chapter 2</h2>
    <p>This chapter explains ba bla bla</p>

    <h2>Chapter 3</h2>
    <p>This chapter explains ba bla bla</p>

    <h2 id="C4">Chapter 4</h2>

</body>

</html>

[6] JS - methods

1) getElementsByClassName('class명');

<script>
  function myFunction() {
  	var x = document.getElementsByClassName('city');
  	for (var i = 0; i < xlength; i++){
		x[i].style.display = "none";
	}	                                 
  }
</script>

2) getElementById('id명');

<script>
  function myFunction() {
  	document.getElementById('myHeader').innerHTML = 'Have a nice day';                                
  }
</script>

profile
안녕하세요, 사용자들의 문제 해결을 중심으로 하는 프론트엔드 개발자입니다. 티스토리로 전환했어요 : https://pangil-log.tistory.com

0개의 댓글