如何让一个元素hover时,让指定区域的产生背景色,在线等?

问题描述

现在一个div高为50px宽为200px,我想让它hover时,只让这个div的高为40px,宽为200px的区域产生背景色,切要居中

相关代码

css

div{
    height: 50px; 
    width: 200px; 
    background: slategrey;
}
div:hover{
    
}

html结构

<div>
    TEST
</div>

有什么解决方法吗?

已解决 悬赏分:30 - 解决时间 2021-11-27 22:51
反对 0举报 0 收藏 0

回答3

最佳
  • @
    div:hover {
      background: linear-gradient(to bottom,slategrey 5px,red 0,red 45px,slategrey 0);
    }
    支持 0 反对 0 举报
    2021-11-27 04:50
  • @

    CSS

    #d1{
        width: 200px; 
        padding: 5px 0;
        background: slategrey;
    }
    #d2{
        height: 40px; 
    }
    #d2:hover{
        background: red;
    }

    HTML

    <div id="d1">
        <div id="d2">TEST</div>
    </div>
    支持 0 反对 0 举报
    2021-11-27 05:41
  • @

    <style>

    .box{
      width: 200px;
      height:50px;
      background: red;
      position: relative;
    }
    .box:hover::after{
      content: " ";
      display: inline-block;
      width: 200px;
      height:40px;
      background: blue;
      position: absolute;
      top:50%;
      left:50%;
      transform: translate(-50%, -50%);
    }

    </style>
    <div class="box"></div>

    上面背景会覆盖内容
    修改后:
    <style>

    .box{
      width: 200px;
      height:50px;
      background: red;
      position: relative;
    }
    .box >div{
      position: relative;
      z-index: 1;
    }
    .box:hover::after{
      content: " ";
      display: inline-block;
      width: 200px;
      height:40px;
      background: blue;
      position: absolute;
      top:50%;
      left:50%;
      transform: translate(-50%, -50%);
    }

    </style>
    <div class="box">

    <div>
      12
    </div>

    </div>

    支持 0 反对 0 举报
    2021-11-27 06:19