Skip to content
sumnail

特定要素以外にスタイルを適用する :not()

created at : 2024/08/09

CSS

:not()擬似クラス

:not()擬似クラスは、特定の要素以外にスタイルを適用するための擬似クラスです。

使用例

ページネーションのボタンで使用例を紹介します。

選択中とそれ以外のページでホバー時の背景色を変えています。

サンプル

vue
<template>
  <div class="container">
    <div v-for="i in 3" :key="i" class="box">
      <button :class="selectedClass(i)" @click="onClick(i)">{{ i }}</button>
    </div>
  </div>
</template>
vue
<script setup lang="ts">
import { ref } from 'vue'

const selected = ref(0)
const selectedClass = (i: number) => {
    return { selected: i === selected.value }
}

const onClick = (i: number) => {
    selected.value = i
}
</script>
vue
<style scoped>
div {
  display: flex;
  gap: 10px;
}

button {
  width: 50px;
  height: 50px;
  background-color: var(--secondary-color);
  border-radius: 50%;
  cursor: pointer;
}

.selected {
  background-color: var(--main-color);
}

.selected:hover {
  background-color: var(--main-hover-color);
}

button:not(.selected):hover {
  background-color: var(--secondary-hover-color);
}
</style>

まとめ

:not()擬似クラスを使用して特定の要素以外にスタイルを適用できます。

参考