개발

[CSS] Attribute selectors란?

dohye1 2022. 11. 3. 11:07
반응형

href$로 쓰는 예시를 봤는데 이 문법이 궁금해서 한번 정리해봄

Attribute selectors

CSS의 attribute selector는 주어진 속성과 일치하는 엘리먼트를 찾는다.

Syntax

[attr]

속성의 이름을 가지고있는 엘리먼트를 의미한다.

/* <a> elements with a title attribute */
a[title] {
  color: purple;
}

만약 title이라는 어트리뷰트를 가지고있는 a태그에 대해 위 스타일이 적용된다.

나는 태그에 내장되어있는 어트리뷰트 이름만 써야한다고 생각했는데 내가 커스텀하게 만든 어트리뷰트도 사용할 수 있다.

예를들면 아래처럼 작성했을때 custom이라는 attr에 정의한 스타일도 적용된다.

<html lang="en">
  <head>
    <style>
      div[title] {
        color: green;
      }

      div[custom] {
        background-color: red;
      }
    </style>
  </head>
  <body>
    <div title="attr" custom="customAttr">예시로 그려짐</div>
  </body>
</html>

그럼 data-로 추가한 속성들을 선택할때 유용할듯!

[attr=value]

특정 attr의 값이 value와 같은 엘리먼트를 나타냄

/* <a> elements with an href matching "https://example.org" */
a[href="https://example.org"]
{
  color: green;
}

[attr~=value]

공백으로 구분된 단어 목록 중 value와 일치하는 것이 있는 엘리먼트를 나타냄.

예를 들면,

<div lang="en-us en-gb en-au en-nz">Hello World!</div>
<div lang="pt">Olá Mundo!</div>
/* All divs in US English are blue. */
div[lang~="en-us"] {
  color: blue;
}

lang attr에서 en-us를 포함하고있는 엘리먼트에 color:blue가 적용된다.

[attr|=value]

attr의 값이 정확히 value와 같거나, 바로 뒤에 -문자가 붙는 value로 시작하는 엘리먼트를 나타낸다.

그래서 종종 language subcode와 일치여부를 확인하는데에 사용된다.

/* All divs in Chinese are red, whether
   simplified (zh-CN) or traditional (zh-TW). */
div[lang|="zh"] {
  color: red;
}

[attr^=value]

value가 prefixed된 값을 가진 속성이 있는 엘리먼트를 나타낸다.

[attr$=value]

value가 suffixed된 값을 가진 속성이 있는 엘리먼트를 나타낸다.

/* Links that start with "https" and end in ".org" */
a[href^="https"][href$=".org"] {
  color: green;
}

그래서 ^$를 위처럼 사용할 수 있음

[attr\*=value]

attr의 값이 value를 포함하고있는 엘리먼트를 나타낸다.

/* <a> elements with an href containing "example" */
a[href*="example"] {
  font-size: 2em;
}

[attr operator value i]

클로징 bracket앞에 i(또는 I)를 적어주게되면 대소문자를 고려하지않고 값을 비교한다.

/* Links with "insensitive" anywhere in the URL,
   regardless of capitalization */
a[href*="insensitive" i] {
  color: cyan;
}

[attr operator value s] Experimental

클로징 bracket앞에 s(또는 S)를 적어주게되면 대소문자를 고려해서 값을 비교한다.

/* Links with "cAsE" anywhere in the URL,
with matching capitalization */
a[href*="cAsE" s] {
  color: pink;
}

참고