代码之家  ›  专栏  ›  技术社区  ›  Jorge

:before和:after伪元素以接收过渡效果

  •  0
  • Jorge  · 技术社区  · 6 年前

    我正在尝试构建一个平行四边形背景,它只出现在菜单项中的悬停位置上。对于形状,我使用了:before和:after伪元素,但是我不能对它们应用相同的过渡效果。有人知道我能做些什么来解决这个问题吗?

    以下是目前为止的代码:

    div {
        float:left;   
        background-color:#fff; 
        margin: 20px;
        transition:.5s;
      
    }
    .testClass {
        margin-top: 0px;
        margin-left: 0px;
        padding: 5px 10px;
        display: block;
        background-repeat: no-repeat;
        background: #fff;
        position: relative;
        transition:.5s;
    
    }
    .testClass:hover {
        background: gold;
        transition:.5s;
    
    }
    .testClass:hover:before {
        content: '';
        position: absolute;
        top:0;
        left:-15px;
        width: 0px;
        height: 0px;
        border-style: solid;
        border-width: 0 0 29px 15px;
        border-color: transparent transparent gold transparent;
    
    }
    .testClass:hover:after {
        content: '';
        position: absolute;
        top:0;
        right:-15px;
        width: 0px;
        height: 0px;
        border-style: solid;
        border-width: 30px 15px 0 0;
        border-color: gold transparent transparent transparent;
    
    }
    <div >
        <div class="testClass">HOME</div>
        <div class="testClass">ABOUT US</div>
        <div class="testClass">CONTACT</div>
        <div class="testClass">LOGIN</div>
        <div class="testClass">SERVICES</div>
    </div>
    1 回复  |  直到 6 年前
        1
  •  3
  •   Temani Afif    6 年前

    使用一个元素创建形状的更简单方法如何:

    div {
      float: left;
      margin: 20px;
      transition: .5s;
    }
    
    .testClass {
      margin-top: 0px;
      margin-left: 0px;
      padding: 5px 10px;
      display: block;
      background: #fff;
      position: relative;
      transition: .5s;
      z-index: 0;
    }
    
    .testClass:before {
      content: '';
      position: absolute;
      z-index: -1;
      top: 0;
      left: -10px;
      right: -10px;
      bottom: 0;
      opacity: 0;
      background: gold;
      transform: skew(-20deg);
      transition: .5s;
    }
    
    .testClass:hover::before {
      opacity: 1;
    }
    <div>
      <div class="testClass">HOME</div>
      <div class="testClass">ABOUT US</div>
      <div class="testClass">CONTACT</div>
      <div class="testClass">LOGIN</div>
      <div class="testClass">SERVICES</div>
    </div>