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

问题描述

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

相关代码

css

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

html结构

<div>
    TEST
</div>

有什么解决方法吗?

阅读 4k
3 个回答
div:hover {
  background: linear-gradient(to bottom,slategrey 5px,red 0,red 45px,slategrey 0);
}

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>

<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>

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题