CSS只悬停在文本上?

问题描述 投票:0回答:4

如果我有以下带有自定义CSS类的HTML:

.custom_list_item {
  color: black;
}

.custom_list_item:hover {
  color: red;
}
<div class="custom_list_item">Test</div>

这使得当我将鼠标悬停在整个盒子上时,它会使文本变为红色。有没有办法确保只有当我将鼠标悬停在文本本身上时才会发生这种情况?

html css text hover
4个回答
5
投票

span包裹它。 p将延伸到div的整个宽度。

.custom_list_item {
    color: black;
}

.custom_list_item span:hover{
    color: red;
}
<div class="custom_list_item"><span>Test</span></div>

2
投票

将其换成跨度然后样式跨度:

.custom_list_item {
  color: black;
}

.custom_list_item span:hover {
  color: red;
}
<div class="custom_list_item">
  <span>Test</span>
</div>

1
投票

将div的display propertyblock改为inline-block。没有必要的额外元素,如跨度。

.custom_list_item {
  color: black;
  display:inline-block;
}

.custom_list_item:hover {
  color: red;
}
<div class="custom_list_item">Test</div>

Div是默认的块级元素,将占用其父元素的整个宽度。


1
投票

您可以为div设置一个范围并设置span:hover

.custom_list_item {
    color: black;
}

span:hover{
    color: red;
}

div{
border: 3px solid red;
}
<div class="custom_list_item"><span>Test</span></div>
© www.soinside.com 2019 - 2024. All rights reserved.