【问题标题】:CSS: How can I change background of a child in response to a hover event on parent? [duplicate]CSS:如何更改孩子的背景以响应父母的悬停事件? [复制]
【发布时间】:2018-10-02 08:55:32
【问题描述】:

在这种情况下,我有一个包含文本 AND<span> 元素。 <span> 有一个 background: black

在悬停其.parent 类时,我希望跨度的背景与悬停.parent 时的父级背景相匹配(即#eee)。

我阅读了有关:host-context 的信息并使用了它,如下面的 sn-p 所示,但它似乎不起作用。我什至在 jsfiddle (link) 中使用了 SCSS,但仍然没有运气。

当父母或曾祖父母.parent悬停时,有没有办法设置孩子.text的背景?

.line {
    text-align: center;
    border-bottom: 1px solid gray;
    line-height: 0.1em;
    width: 100%;
    margin: 10px 0 20px;
}
.text {
    color: green;
    background: black;
    padding: 0 10px;
}

.parent {
  background: #000;
  display: flex;
  align-items: center;
  height:100px;
}


.parent:hover {
  background: #eee;
}

:host-context(.parent:hover) {
  .text {
    background: #eee;
  }
}
<div class="parent">
  
  <div class="line" style="">
    <span class="text">AND</span>
  </div>
</div>

【问题讨论】:

    标签: css css-selectors


    【解决方案1】:

    只需将.parent:hover .text 用作选择器:当.parent 悬停时,它将应用于.parent 内的.text

    .line {
        text-align: center;
        border-bottom: 1px solid gray;
        line-height: 0.1em;
        width: 100%;
        margin: 10px 0 20px;
    }
    .text {
        color: green;
        background: black;
        padding: 0 10px;
    }
    
    .parent {
      background: #000;
      display: flex;
      align-items: center;
      height:100px;
    }
    
    
    .parent:hover {
      background: #eee;
    }
    
    .parent:hover .text {
      background: #eee;
    }
    <div class="parent">
      
      <div class="line" style="">
        <span class="text">AND</span>
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 2012-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-12
      • 2013-11-07
      • 1970-01-01
      • 2018-08-11
      相关资源
      最近更新 更多