4

If I have the following HTML with a custom CSS class:

.custom_list_item {
  color: black;
}

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

This makes it so when I hover over the entire box, it makes the text red. Is there a way to make sure this only happens when I hover over just the text itself?

3
  • you can wrap the text inside a paragraph element and add your style to it. Is it clear to you?
    – Alessio
    Mar 18, 2019 at 16:14
  • As @08691 said below, this is a simple display concept. A div by default has display block, so that div gets the full space available. If you want that .custom_list_item. get only the content width, just you have to modify block display by default given to DIVs with display: inline-block; Just: .custom_list_item {display: inline-block; color: black; } Mar 18, 2019 at 16:36
  • @AlbertoFortes No, actually that's not what I'm trying to accomplish. Since this is meant to be used as a list item, if I set the display to inline-block it would still hover on the entire box if there is another element that has a wider content block. The span works perfectly. Mar 18, 2019 at 16:42

4 Answers 4

9

Wrap it in a span. A p would stretch over the full width of div.

.custom_list_item {
    color: black;
}

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

1
  • Yes thanks, this is perfect. I was using a p earlier, and realized that it didn't help my situation. Mar 18, 2019 at 16:34
3

Wrap it in span then style span:

.custom_list_item {
  color: black;
}

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

2
  • If you change p to span you have a working solution ;) Mar 18, 2019 at 16:21
  • Yea. That's a better Idea. Updated my answer in respect of your advice and reputation :) Thanks. Mar 18, 2019 at 16:23
1

Change that div's display property from block to inline-block. No extra elements like spans necessary.

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

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

Divs are block level elements by default and will take up the full width of their parent element.

1

You can wrap a span for your div and set 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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.