HTML

14. HTML 클래스 (class)

하둉이 2019. 1. 7. 21:36
반응형

* HTML class *


: HTML class 속성은 동일한 클래스 이름을 가진 요소에 대해 동일한 스타일을 정의하는데 사용됩니다.

  따라서 동일한 class 속성을 가진 모든 HTML 요소는 동일한 형식 및 스타일을 갖습니다.

  


EX)

<!DOCTYPE html>
<html>
<head>


<style>
.cities {        
  background-color: black;    //배경 색 : black
  color: white;               //글자 색 : white 
  margin: 20px;               //상하 좌우 모두 20px의 간격 (바깥쪽 여백)
  padding: 20px;              //
상하 좌우 모두 20px의 간격 (안쪽 여백)
} 

</style>


</head>

<body>

<div class="cities">    // cities의 이름을 가진 클래스 사용
  <h2>런던</h2>
  <p>London is the capital of England.</p>
</div>

<div class="cities">    // cities의 이름을 가진 클래스 사용
  <h2>파리</h2>
  <p>Paris is the capital of France.</p>
</div>

<div class="cities">    // cities의 이름을 가진 클래스 사용


  <h2>도쿄</h2>
  <p>Tokyo is the capital of Japan.</p>
</div>

</body>
</html>


  실행 결과 


- TIP (margin / padding) -> 위의 예제 참고




* 여러 클래스 *

: HTML 요소는 class를 두개 이상 가질 수 있으며 각 class 이름은 공백으로 구분해야 합니다.


EX)

<!DOCTYPE html>
<html>
<head>


<style>
.city {                          //city 클래스
    background-color: tomato;    //배경 색 : tomato
    color: white;                //글자 색 : white
    padding: 10px;               //
상하 좌우 모두 10px의 간격 (안쪽 여백)
} 


.main {                        //main 클래스
    text-align: center;        //글자 정렬 : center(중앙)
} 


</style>

<h2 class="city main">London</h2>    //city와 main 클래스에 포함된 효과를 모두 적용

<h2 class="city">Paris</h2>

<h2 class="city">Tokyo</h2>


</body>
</html>

  실행 결과 



* JavaScript의 class 속성 사용 *

: JavaScript는 getElementsByClassName( ) 메소드를 사용하여 지정된 클래스 이름을 가진 요소에 액세스 할 수 있습니다.


EX)

<!DOCTYPE html>
<html>
<head>


<h2 class="city">London</h2>

<p>London is the capital of England.</p>

<h2 class="city">Paris</h2>

<p>Paris is the capital of France.</p>

<h2 class="city">Tokyo</h2>

<p>Tokyo is the capital of Japan.</p>


<script>    //자바 스크립트 부분
function myFunction() {

  //사용자가 버튼을 클릭하면 이름이 "city"인 모든 요소를 숨깁니다.
  var x = document.getElementsByClassName("city");
  for (var i = 0; i < x.lengthi++) {
    x[i].style.display = "none";
  }
}
</script>


</body>
</html>

  실행 결과 ( 버튼 클릭 전 -> 버튼 클릭 후)








반응형