CSS :hover 选择器

毋承基
2023-12-01

1. 聚焦改变自己

.style1:hover

:hover前面空格,给最外层parentss设置hover样式(背景变为红色)

<div class="parentss">
  床前明月光
  <div class="childss1">踏破铁鞋无觅处</div>
  <div class="childss2">得来全不费工夫</div>
  <div class="childss3">举头望明月</div>
  <div class="childss4">低头思故乡</div>
</div>

<style>
.parentss:hover {
  background-color: red;
}
</style>

 .style1 :hover

:hover前面空格,给parentss的直接子元素设置hover样式(背景变为红色)

<div class="parentss">
  床前明月光
  <div class="childss1">踏破铁鞋无觅处</div>
  <div class="childss2">得来全不费工夫</div>
  <div class="childss3">举头望明月</div>
  <div class="childss4">低头思故乡</div>
</div>

<style>
.parentss :hover {
  background-color: red;
}
</style>

2. 聚焦我,改变我的子元素(父对子)

<div class="parentss">
  床前明月光
  <div class="childss">踏破铁鞋无觅处</div>
</div>

<style>
.parentss{
  color: blue;
}
.parentss:hover .childss{
  color: red;
  background: rebeccapurple;
}
</style>

3. 聚焦我,改变我相邻的兄弟元素(聚焦childss1,改变childss2)

注意:childss1 和 childss2 必须是同级相邻元素

<div class="parentss">
  床前明月光
  <div class="childss1">踏破铁鞋无觅处</div>
  <div class="childss2">得来全不费工夫</div>
</div>

<style>
.childss1:hover + .childss2{
  color: red;
}
</style>

4. 聚焦我,改变不相邻的兄弟元素(聚焦childss1,改变childss3或者childss4)

注意:必须元素是同级

<div class="parentss">
  床前明月光
  <div class="box1">
    <div class="childss1">踏破铁鞋无觅处</div>
    <div class="childss2">得来全不费工夫</div>
    <div class="childss3">举头望明月</div>
    <div class="childss4">低头思故乡</div>
  </div>
</div>

<style>
.childss1:hover ~ .childss3 {
  color: red;
}
.childss1:hover ~ .childss4 {
  color: red;
}
</style>

CSS :hover 选择器

 类似资料: