Kaigai Blog living abroad in my twenties

【My Study Note】Widely used selectors

CSS Programming

Widely used selectors

Attribute Selectors

CSS [attribute] Selector

a[class] {
  background-color: yellow;
}

CSS [attribute=”value”] Selector

a[class="example"] {
  background-color: yellow;
}

CSS [attribute~=”value”] Selector

/* This selects all elements with a class attribute that contains "flower" */
[class~="flower"] {
  border: 5px solid yellow;
}

The [attribute~=”value”] selector is used to select elements with an attribute value containing a specified word.

[attribute|=”value”]

/* These 2 would be selected */
<h1 class="top-header">Welcome</h1>
<p class="top-text">Hello world!</p>
/* This would not be selected */
<p class="topcontent">Are you learning CSS?</p>
CSS [attribute|="value"] Selector

[class|=top] { background: yellow; }

The [attribute|=”value”] selector is used to select elements with the specified attribute, whose value can be exactly the specified value, or the specified value followed by a hyphen (-).

CSS [attribute^=”value”] Selector

[class^="top"] {
  background: yellow;
}

The [attribute^=”value”] selector is used to select elements with the specified attribute, whose value starts with the specified value.

CSS [attribute$=”value”] Selector

[class$="test"] {
  background: yellow;
}

The [attribute$=”value”] selector is used to select elements whose attribute value ends with a specified value.

CSS [attribute*=”value”] Selector

[class*="te"] {
  background: yellow;
}

The [attribute*=”value”] selector is used to select elements whose attribute value contains a specified value.

:nth-of-type()

<div>
<p>This is some text.</p>
</div>
<!-- This would be called 👇 -->
<div>
<p>This is some text.</p>
</div>
<div>
<p>This is some text.</p>
</div>
/* Selects the second element of div siblings */
div:nth-of-type(2) {
  background: red;
}

The :nth-of-type(n) selector matches every element that is the nth child, of the same type (tag name), of its parent.

:nth-child()

<div>
  <p>This is some text.</p>
</div>
<div>
  <p>This is some text.</p>
</div>
<!-- This would be called 👇 -->
<div>
  <p>This is some text.</p>
</div>
<ul>
  <li>First list item</li>
  <li>Second list item</li>
  <!-- This would be called 👇 -->
  <li>Third list item</li>
  <li>Fourth list item</li>
  <li>Fifth list item</li>
</ul>
/* Selects every third element among any group of siblings */
:nth-child(3) {
  background: yellow;
}

The :nth-child(n) selector matches every element that is the nth child of its parent.

:nth-of-type()と:nth-child()の違いは、:nth-of-type()がその要素の中での順番を指定するのに対して、:nth-child()はその要素の子要素の中での順番を探せる。役に立つ記事