[CSS] 속성 선택자 알아보기

hejuby·2024년 2월 18일

속성 선택자(Attribute Selector)란 특정 속성이 있는 요소를 지정하여 매칭할 수 있는 선택자입니다. 속성의 값이나 그 서브스트링에 대한 옵션을 지정할 수도 있습니다.

문법

[attr]

attr 속성이 있는 요소를 선택합니다.

[hidden] {
  /* hidden 속성이 포함된 요소 선택 */
  display: none;
}

[attr=value]

attr 속성의 값이 value와 정확하게 일치하는 요소를 선택합니다.

<input type="text" placeholder="Enter your nickname" />
[type="text"] {
  /* type 속성이 "text"인 요소 선택 */
  outline: none;
}

[attr~=value]

attr 속성의 (공백으로 구분된) 값 중 하나가 value와 일치하는 요소를 선택합니다. 속성의 값이 하나라도 동작합니다.

<div class="item green">
  I'm selected!
</div>
<div class="item blue">
  I am not selected.
</div>
<div class="item red">
  I am not selected.
</div>
[class~="green"] {
  /* 클래스 중 하나가 "green"인 요소를 선택 */
  padding: 20px;
  background-color: green;
}

[attr|=value]
attr 속성의 값이 value와 일치하거나 value 바로 다음 하이픈('-')으로 시작하는 요소를 선택합니다.

[lang|="zh"] {
  /* lang 속성이 "zh"이거나 "zh-"로 시작하는 요소 선택 */
}

[attr^=value]
attr 속성의 값이 value로 시작하는 요소를 선택합니다.

[lang^="en"] {
  /* lang 속성이 "en"으로 시작하는 모든 요소를 선택 */
}

[attr$=value]
attr 속성의 값이 value로 끝나는 요소를 선택합니다.

<div class="content-wrapper">
  I'm selected!
  <div class="img-wrapper">
    I'm selected too!
  </div>
</div>
<div>
  I am not selected.
</div>
[class$="wrapper"] {
  /* "wrapper"로 끝나는 클래스를 가진 요소를 선택 */
  border: 1px solid red;
}

[attr*=value]
attr 속성의 값이 value를 포함하는 문자열인 요소를 선택합니다.

[href*=".com"] {
  /* href 값에 ".com"이 포함된 요소 선택 */
}

속성 선택자 마지막에 i 또는 s 를 포함하면 대소문자 구분 여부(Case sensitivity)를 명시할 수 있습니다.

[class*="username" i] { /* ... */ } /* 대소문자 구분 안함 */
[class*="username" s] { /* ... */ } /* 대소문자 구분 */

예시

다음은 Tailwind Css의 Normalize인 preflight.css 입니다. (줄 수를 줄이기 위해 의도적으로 공백을 제거했습니다.)
이 코드에서도 속성 선택자가 여러번 활용된 것을 확인할 수 있습니다.

*,::before,::after{box-sizing:border-box;border-width:0;border-style:solid;border-color:theme('borderColor.DEFAULT', currentColor);}
::before,::after{--tw-content:'';}
html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;font-family:theme('fontFamily.sans',ui-sans-serif,system-ui,sans-serif,"AppleColorEmoji","SegoeUIEmoji","SegoeUISymbol","NotoColorEmoji");font-feature-settings:theme('fontFamily.sans[1].fontFeatureSettings',normal);font-variation-settings:theme('fontFamily.sans[1].fontVariationSettings',normal);-webkit-tap-highlight-color:transparent;}body{margin:0;line-height:inherit;}
hr{height:0;color:inherit;border-top-width:1px;}
abbr:where([title]){text-decoration:underlinedotted;}
h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit;}
a{color:inherit;text-decoration:inherit;}
b,strong{font-weight:bolder;}
code,kbd,samp,pre{font-family:theme('fontFamily.mono',ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"LiberationMono","CourierNew",monospace);font-feature-settings:theme('fontFamily.mono[1].fontFeatureSettings',normal);font-variation-settings:theme('fontFamily.mono[1].fontVariationSettings',normal);font-size:1em;}
small{font-size:80%;}
sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline;}
sub{bottom:-0.25em;}
sup{top:-0.5em;}
table{text-indent:0;border-color:inherit;border-collapse:collapse;}
button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;color:inherit;margin:0;padding:0;}button,select{text-transform:none;}
button,[type='button'],[type='reset'],[type='submit']{-webkit-appearance:button;background-color:transparent;background-image:none;}
:-moz-focusring{outline:auto;}
:-moz-ui-invalid{box-shadow:none;}
progress{vertical-align:baseline;}
::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto;}
[type='search']{-webkit-appearance:textfield;outline-offset:-2px;}
::-webkit-search-decoration{-webkit-appearance:none;}
::-webkit-file-upload-button{-webkit-appearance:button;font:inherit;}
summary{display:list-item;}
blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0;}
fieldset{margin:0;padding:0;}
legend{padding:0;}
ol,ul,menu{list-style:none;margin:0;padding:0;}
dialog{padding:0;}
textarea{resize:vertical;}
input::placeholder,textarea::placeholder{opacity:1;color:theme('colors.gray.400',#9ca3af);}
button,[role="button"]{cursor:pointer;}
:disabled{cursor:default;}
img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle;}
img,video{max-width:100%;height:auto;}
[hidden]{display:none;}
button, [type='button'], [type='reset'], [type='submit'] {
  -webkit-appearance: button;
  background-color: transparent;
  background-image: none;
}

button 태그, type이 'button'인 요소, 'reset'인 요소, 'submit'인 요소를 찾아 배경색과 배경 이미지를 초기화해줍니다.

[type='search'] {
  -webkit-appearance: textfield;
  outline-offset: -2px;
}

type이 'search'인 요소의 outline-offset을 -2px로 통일해줍니다.

button, [role="button"] {
  cursor: pointer;
}

button 태그, 그리고 role이 "button"인 요소에 cursor 속성을 지정해줍니다.

[hidden] {
  display: none;
}

hidden 속성이 부여된 요소를 출력하지 않습니다.

이와 같이 속성 선택자를 활용하면 여러가지 요소들을 효과적으로 선택할 수 있습니다.

참고문헌

https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors/Attribute_selectors
https://velog.io/@teo/2022-CSS-Reset-다시-써보기

0개의 댓글