【问题标题】:CSS Conditional Statements with hover带悬停的 CSS 条件语句
【发布时间】:2019-07-19 16:03:14
【问题描述】:

这个问题在条件 CSS 中可能更简单。

我有五行包含一些内容,根据某些条件,我添加了一个名为 'previous' 的类来显示不同的背景颜色。

当我将鼠标悬停在上一个课程内容时,我得到了透明的背景,这不好。

我想显示相同的背景颜色(灰色),即使它被悬停。

所以,我尝试了下面的代码并尝试在 css 中使用 :has 条件,如果它有以前的类,则将悬停颜色更改为灰色。但它没有用。

我的期望是即使悬停也有相同的背景颜色。

有人可以帮我解决这个问题,因为我只需要 CSS/SCSS 的解决方案。不是来自 javascript。

.previous {
  background-color: grey;
}
.row:hover {
  background-color: transparent;
  :has(.previous) {
      background-color: grey;
  }
}
<div class="row">Some Content 1</div>
<div class="row previous">Some Content 2</div>
<div class="row">Some Content 3</div>
<div class="row previous">Some Content 4</div>
<div class="row">Some Content 5</div>

【问题讨论】:

    标签: html css sass


    【解决方案1】:

    您可以使用:not 伪类执行此操作,以从悬停效果中排除具有previous 类的行。现在:hover 将在每个具有.row 类但又不具有.previous 类的元素上运行。

    .row {
      background-color: lightblue;
    }
    
    .previous {
      background-color: grey;
    }
    
    .row:not(.previous):hover {
      background: transparent;
    }
    <div class="row">Some Content 1</div>
    <div class="row previous">Some Content 2</div>
    <div class="row">Some Content 3</div>
    <div class="row previous">Some Content 4</div>
    <div class="row">Some Content 5</div>

    【讨论】:

    • 谢谢,我们需要将颜色更改为背景:透明以使其工作 :) 感谢使用 :not condition :)
    • 红色只是为了演示更好的展示你可以在代码中使用任何颜色的效果,这里的重点是选择器。
    【解决方案2】:

    为什么不只是改变你的选择器的顺序,也为上一个类添加一个悬停:

    .row:hover {
      background-color: transparent;
    }
    
    .previous,
    .previous:hover {
      background-color: grey;
    }
    <div class="row">Some Content 1</div>
    <div class="row previous">Some Content 2</div>
    <div class="row">Some Content 3</div>
    <div class="row previous">Some Content 4</div>
    <div class="row">Some Content 5</div>

    此外,如果您想要与前一个类的行,您只需组合选择器:.row.previous

    :has 是 css4,支持很少:https://developer.mozilla.org/en-US/docs/Web/CSS/:has

    【讨论】:

    • 伟大的解决方案皮特 :) 谢谢
    【解决方案3】:

    这是一个纯 css 解决方案。

    您可以为悬停设置不同的样式,无论它是否具有上一个类。

    .row:hover {
      background-color: transparent;
    }
    .row.previous {
      background-color: grey;
    }
    .row.previous:hover {
      background-color: #595959; /*any color really*/
    }
    <div class="row">Some Content 1</div>
    <div class="row previous">Some Content 2</div>
    <div class="row">Some Content 3</div>
    <div class="row previous">Some Content 4</div>
    <div class="row">Some Content 5</div>

    【讨论】:

      猜你喜欢
      • 2013-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-16
      • 1970-01-01
      • 2011-05-05
      相关资源
      最近更新 更多