오늘은 css에서 유용하게 사용할 수 있는 variable과
html에서 로직을 빠르게 구현해보고 싶을때 유용하게 활용 가능한 data attribute에 대해 배웠다.
CSS variable
css에서도 JS 처럼 변수를 선언하고 재사용할 수 있는 기능이 있다.
syntax는 아래와 같다.
:root{
--font-size : 16px;
--background-color : whitesmoke;
--text-color : darkblue;
--base-space : 8px;
}
.first{
margin-left: calc(var(--base-space) *2);
}
@media screen and (max-width: 768px){
:root{
--text-color: purple;
--base-space: 4px;
}
}
위와 같이 --변수명 : 값 으로 지정하고, var(--변수명)으로 사용이 가능하다.
또, :root{}에 변수를 지정하면 global 변수로 사용이 가능하다.
지정한 변수는 아래 .first{}에 사용한 것과 같이 사용이 가능하다.
또한, css에서는 calc() 함수를 제공하여, 변수에 연산이 가능하다.
하나 더 유용한 포인트로는, 미디어쿼리에서의 활용이다.
미디어쿼리 안에서 root:{}를 지정하고 local 변수로 선언과 활용이 가능하다.
로컬 변수가 우선순위가 있어 글로벌 변수의 지정 값은 무시된다.
HTML data* atrribute
data-* attributes allow us to store extra information on standard, semantic HTML elements without other hacks such as non-standard attributes, or extra properties on DOM.
from MDN data attribute
- syntax : data-*
<div data-index="1" data-display-name="hopper"></div>
<div data-index="2" data-display-name="coder"></div>
<span data-index="1" data-display-name="hopper">hello hopper</span>
- css access
- [data-display-name=’hopper’] 으로 지정하면, 첫번째 div와 세번째줄 span 모두에 적용이 된다
- div[data-display-name=’hopper’] 으로 지정하여 첫번째 div 테그에만 스타일 적용 가능하다
div {
width: 50px;
height: 50px;
background-color: orangered;
margin-bottom: 50px;
}
div[data-display-name='hopper']{
background-color: yellow;
}
- JS access
- document.querySelector 메소드를 사용하여 해당 데이터를 상수변수로 만들어준다
- 이때, JS에서는 display-name → displayName 으로 camel case 화 함
- 'div[data-display-name="hopper"]' → 따옴표 안에 또 따옴표를 사용해야 할 경우, 홑겹을 먼저 사용했다면, ㅇ쌍겹을 사용해야 string으로 인식이 가능하다.
const hopper = document.querySelector('div[data-display-name="hopper"]')
console.log(hopper.dataset);
console.log(hopper.dataset.displayName);
- - : HTML에 적는 모든 키와 밸류는 브라우저에 접속하는 모든 사람이 access 가능하므로 보안이 필요한 값은 입력DOM 요소에 입력하지 말아야 한다.
- + : 기능 로직 등을 빠르게 처리하기 위해서는 유용한 방법이다.
'TIL(today i learned)' 카테고리의 다른 글
[project] 포트폴리오 웹사이트 markup (0) | 2022.04.29 |
---|---|
[html/css] BEM (0) | 2022.04.28 |
[JS] web APIs (0) | 2022.04.25 |
[JS] API 개념, async vs defer (0) | 2022.04.25 |
[VS code] emmet 설정하고 사용하기 (0) | 2022.04.25 |