【问题标题】:Hover effect does not activate other element [duplicate]悬停效果不会激活其他元素[重复]
【发布时间】:2020-09-01 06:19:35
【问题描述】:

出于某种原因

#item1:hover ~ #item1::before{ display: block; }

当我将鼠标悬停在#item 1 上时,实际上并没有在块中显示我想要的元素。

这是代码,提前致谢! https://jsfiddle.net/dyus45w0/

【问题讨论】:

    标签: html css hyperlink hover display


    【解决方案1】:

    更改 CSS

    * {
        margin: 0;
        padding: 0;
    }
    
    header {
        display: flex;
        justify-content: space-between;
        background: #2a2e33;
        align-items: center;
        width: 100%;
        height: 60px;
        position: relative;
    }
    
    #logo {
        color: white;
        margin-left: 10px;
        position: relative;
    }
    
    
    #list {
        display: flex;
        height: 100%;
        list-style: none;
        color: white;
    }
    
    li {
        padding-left: 10px;
        padding-right: 10px;
        padding-top: 20px;
        max-height: 100%;
        position: relative;
    }
    
    
    li:hover {
        background: #1e2329;
    }
    
    
    li::before {
        content: "";
        background-color: chocolate;
        width: 100%;
        height: 4px;
        position: absolute;
        top: 0;
        left: 0;
        display: none;
    }
    
    li:hover::before {
        display: block;
    }
      <header>
        <h1 id="logo">LOGO</h1>
        <ul id="list">
          <li id="item1">HOME</li>
          <li id="item2">ABOUT US</li>
          <li id="item3">CONTACT</li>
          <li id="item4">BLOG</li>
        </ul>
    </header>

    【讨论】:

    • 谢谢拉尔吉!我已经为此苦苦挣扎了一段时间
    【解决方案2】:

    符号~ 是通用兄弟组合子。来自MDN docs

    通用兄弟组合符 (~) 分隔两个选择器,并且仅当第二个元素跟在第一个元素之后(尽管不一定立即)匹配第二个元素,并且它们都是同一个父元素的子元素。

    您的元素#item1 没有兄弟#item1,因为它就是该元素本身。换句话说,一个元素不能跟随它自己。

    这意味着你的 CSS 选择器不能匹配任何元素,因为没有两个元素可以有相同的id

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-30
      • 2013-06-08
      • 2014-10-25
      • 2012-03-18
      • 1970-01-01
      • 2017-05-18
      • 2013-04-26
      • 1970-01-01
      相关资源
      最近更新 更多