首页 > 解决方案 > CSS:在悬停时更改元素的背景:仅更改孩子的背景而不是父母的(小提琴,图片)

问题描述

我有这个代码:

html

<div class="item">
  <p>hello</p>
</div>

CSS

.item {
    border: 2px dashed green;
    background-color: red;
    width: 100px;
    height: 100px;
    margin-left: 30px;
    margin-top: 30px;
}

.item :hover  {
   background-color: yellow;
}

我试图在悬停时将所有项目的颜色更改为黄色。但是,只有文本的背景颜色会发生变化:

在此处输入图像描述

虽然我想要这个:

在此处输入图像描述

小提琴:https ://jsfiddle.net/87qd0au9/

标签: javascripthtmlcss

解决方案


删除项目和悬停之间的空间

.item:hover  {
  background-color: yellow;
}

推荐阅读