Computer >> 컴퓨터 >  >> 프로그램 작성 >> CSS

CSS에서 데이터 속성(data-*) 사용

<시간/>

data-* 속성을 사용하여 요소에 대한 추가 정보를 저장할 수 있습니다. 다음 예는 CSS data-* 속성을 보여줍니다.

예시

<!DOCTYPE html>
<html>
<head>
<style>
dl {
   margin: 2%;
}
p {
   width: 60%;
   background-color: lightgreen;
   padding: 2%;
   color: white;
   text-align: center;
}
dt {
   font-weight: bold;
}
dt:hover {
   cursor: pointer;
}
dd {
   font-style: italic;
}
</style>
</head>
<body>
<dl>
<dt onmouseover="showDescription(this)" data-food-type="beverages">Tea</dt>
<dd>Hot Spicy Tea or Ice Lemon Tea </dd>
<dt onmouseover="showDescription(this)" data-food-type="snacks">Toast</dt>
<dd>Hot Garlic Butter Toast</dd>
</dl>
<p>(hover over food item)</p>
</body>
<script>
function showDescription(food) {
   let foodType = food.getAttribute("data-food-type");
   document.querySelector('p').textContent = ("We have " + food.innerHTML + " in " + foodType + ".");
}
</script>
</html>

출력

이것은 다음과 같은 결과를 생성합니다 -

CSS에서 데이터 속성(data-*) 사용

예시

<!DOCTYPE html>
<html>
<head>
<style>
section {
   margin: 8%;
   box-shadow: inset 0 0 20px red;
   width: 300px;
   padding: 2%;
}
section[data-number='77'] {
   height: 120px;
   border-radius: 15px;
}
section::before {
   content: attr(data-user);
   font-size: 1.2em;
}
section::after {
   content: attr(data-number);
}
</style>
</head>
<body>
<section data-number="77" data-user="Client">
<p>Demo Text</p>
</section>
</body>
</html>

출력

이것은 다음과 같은 결과를 생성합니다 -

CSS에서 데이터 속성(data-*) 사용