웹 개발

HTML class 속성에서 hyphen/dash(-)를 사용하는 이유

노루아부지 2021. 11. 19. 17:58

인터넷에서 jquery plugin이나 다른 script, css 파일을 보면 css selector의 구분자가 모두 underscore(_)가 아닌 hyphen(-)로 되어있는 것을 볼 수 있습니다.

 

그런데 이상합니다. user_name같이 understore로 되어있으면 더블클릭 시 user_name이 모두 선택되는데, user-name이면 더블클릭하면 클릭한 쪽의 단어만 선택이 됩니다.

 

분명히 이렇게 불편한데 왜 hyphen(dash)를 사용하는 것일까요?

 

여러 가지 이유가 있지만 가장 큰 이유는 css의 공식 구분자가 dash 때문인 것 같습니다.

 

첫 번째로, 과거에 하위 브라우저를 지원해줘야 하는 일이 있었는데, 특정 브라우저에서 underscore가 포함된 class명을 인식하지 못해서 동작하지 않는 경우가 발생했습니다

CSS1의 사양에서는 class 및 ID 이름에 underscore를 사용하는 것을 허용하지 않았다고 하는데, 이것에 영향인 것 같기도 합니다.

 

두 번째로는 CSS가 공식적으로 지원하는 구분자가 hyphen이기 때문에 dash를 사용해야 selector를 사용할 수 있는데 대표적으로 |= attribute selector가 있습니다.

(camel case를 사용하지 말아야 하는 이유가 될 것 같습니다.)

 

예를 들어, 아래와 같은 selector가 있다고 가정하면

span[class|="em"] { font-style: italic; }

 

아래 2개의 class 모두 적용됩니다.

<span class="em">I'm italic</span>
<span class="em-strong">I'm italic too</span>

 

 

 

[참고]

https://stackoverflow.com/questions/7560813/why-are-dashes-preferred-for-css-selectors-html-attributes

 

Why are dashes preferred for CSS selectors / HTML attributes?

In the past I've always used underscores for defining class and id attributes in HTML. Over the last few years I changed over to dashes, mostly to align myself with the trend in the community, not

stackoverflow.com

 

728x90
loading