Best practices for styling highlighted text when hovered over using CSS

Here is a link to the codepen in question: https://codepen.io/dvreed77/pen/yrwjoM.

I am trying to highlight specific text with a large line gap and maintain the hover effect consistently when hovering over individual blocks of text. Currently, the highlight flashes rapidly on-off-on when moving over the whitespace between lines.

I have attempted adjusting the height and other properties, but nothing seems to solve the issue and I am a bit stuck.

The relevant CSS code can be found below:

div {
  width: 90%; /* Adjusted for styling */
  margin: 0 auto;
  line-height: 2;
}

span {
  height: 2em;
  background: rgba(255, 0, 0, 0.2);
  vertical-align: middle;
}

span:hover {
  background: rgba(255, 0, 0, 0.5);
}
<div>
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi hendrerit, enim eu fermentum condimentum, nulla tellus suscipit libero, quis tincidunt eros metus sed leo.</span> 
  <span>Suspendisse eu augue lectus.</span>
  <span>Sed aliquam pulvinar nibh eu vulputate. Sed venenatis eros at nisl ornare sollicitudin. Duis nec est gravida, sodales orci in, blandit magna.</span>            
  <span>Donec semper sodales lacus vel consequat.</span>
  <span>Mauris augue lectus, pretium eget dui interdum, iaculis dictum erat.</span>
  <span>Pellentesque sed nulla blandit, suscipit risus eu, malesuada justo.</span>
  <span>Fusce in dignissim magna. Quisque at tincidunt mauris.</span>
  <span>Fusce augu.... (The code has been truncated for brevity)
  <span> Vestibulum ut ultricies neque.</span>
</div>

Answer №1

In this method, a clever hack using pseudo elements is employed to expand the hoverable area of a span and cover the space between the lines.

div {
  width: 90%; /* Adjusted to fit the JS-Snippet layout */
  margin: 0 auto;
  line-height: 2;
  position:relative; /* Relative to the div, not the span! */
  z-index:0;
  overflow:hidden; /* Hide the overflow of the pseudo element */
}

span {
  background: rgba(255, 0, 0, 0.2);
  vertical-align: middle;
}

span:hover {
  background: rgba(255, 0, 0, 0.5);
}
span:before {
  content:"";
  position:absolute;
  /* Do not set any top and bottom value! */
  left:0;
  right:0;
  height:100vh; /* a large height */
  z-index:-2;
}
/* Make the pseudo element appear on top of all others on span hover */
span:hover:before {
  z-index:-1;
}
<div>
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi hendrerit, enim eu fermentum condimentum, nulla tellus suscipit libero, quis tincidunt eros metus sed leo.</span> 
  <span>Suspendisse eu augue lectus.</span>
  <span>Sed aliquam pulvinar nibh eu vulputate. Sed venenatis eros at nisl ornare sollicitudin. Duis nec est gravida, sodales orci in, blandit magna.</span>            
  <span>Donec semper sodales lacus vel consequat.</span>
  <span>Mauris augue lectus, pretium eget dui interdum, iaculis dictum erat.</span>
  <span>Pellentesque sed nulla blandit, suscipit risus eu, malesuada justo.</span>
  <span>Fusce in dignissim magna. Quisque at tincidunt mauris.</span>
  <span>Fusce augu...

Another approach involves utilizing vertical padding (that doesn't impact the layout) combined with background-clip.

div {
  width: 90%; /* Adjusted to fit the JS-Snippet layout */
  margin: 0 auto;
  line-height: 2;
  position:relative; /* Relative to the div, not the span! */
  z-index:0;
  overflow:hidden; /* Hide the overflow of the pseudo element */
}

span {
  background-color: rgba(255, 0, 0, 0.2);
  vertical-align: middle;
  padding:1em 0; /* Increase the clickable area */
  background-clip:content-box; /* Show background only within content */
}

span:hover {
  background-color: rgba(255, 0, 0, 0.5);
}
<div>
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi hendrerit, enim eu fermentum condimentum, nulla tellus suscipit libero, quis tincidunt eros metus sed leo.</span> 
  <span>Suspendisse eu augue lectus.</span>
  <span>Sed aliquam ...

Answer №2

One possible solution could be implementing scaffolding.

.main {
  width: 20%;
  margin: 0 auto;
  line-height: 2;
  border: 1px solid;
}

span {
  height: 2em;
  background: rgba(255, 0, 0, 0.2);
  vertical-align: middle;
  border: 1px solid;
}

.scaffolding:hover>span {
  background: rgba(255, 0, 0, 0.5);
}
<div class="main">
  <div class="scaffolding "> <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi hendrerit, enim eu fermentum condimentum, nulla tellus suscipit libero, quis tincidunt eros metus sed leo.</span></div>
  <div class="scaffolding "> <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi hendrerit, enim eu fermentum condimentum, nulla tellus suscipit libero, quis tincidunt eros metus sed leo.</span></div>
  <div class="scaffolding "> <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi hendrerit, enim eu fermentum condimentum, nulla tellus suscipit libero, quis tincidunt eros metus sed leo.</span></div>
</div>


Another alternative is utilizing borders that match the background color, although this may require finding a suitable border width to match the font size and ensuring no space between tags in the markup.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

div {
  width: 90%;
  margin: 0 auto;
  line-height: 2;
}

span {
  background: rgba(255, 0, 0, 0.2);
  border: 8px solid #fff;
}

span:hover {
  background: rgba(255, 0, 0, 0.5);
}
<div>
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi hendrerit, enim eu fermentum condimentum, nulla tellus suscipit libero, quis tincidunt eros metus sed leo.</span><span>Suspendisse eu augue lectus.</span><span>Sed aliquam pulvinar nibh eu vulputate. Sed venenatis eros at nisl ornare sollicitudin. Duis nec est gravida, sodales orci in, blandit magna.</span><span>Donec semper sodales lacus vel consequat.</span><span>Mauris augue lectus, pretium eget dui interdum, iaculis dictum erat.</span><span>Pellentesque sed nulla blandit, suscipit risus eu, malesuada justo.</span><span>Fusce in dignissim magna. Quisque at tincidunt mauris.</span><span>Fusce augue mauris, ornare eget lorem sed, bibendum lacinia justo.</span><span>Nullam et vestibulum neque.</span><span>Duis eget mauris elementum leo scelerisque dignissim accumsan tempor ex.</span><span>Donec facilisis sollicitudin urna, sed efficitur ex ornare at.</span><span>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</span><span>Duis at sem nibh. Sed sagittis velit sed ex tincidunt gravida facilisis eu augue.</span><span>Aenean dapibus sem et dolor venenatis facilisis. Sed arcu tortor, luctus id felis quis, venenatis malesuada leo. Fusce vitae semper lacus.</span><span>Phasellus magna eros, lobortis a faucibus a, elementum et sem. Nunc porta auctor arcu, eu viverra tellus vestibulum id. Morbi consequat sed magna id aliquam.</span><span>Donec vehicula odio nec ullamcorper ornare.</span><span> Vestibulum ut ultricies neque.</span>  
</div>

Answer №3

To achieve this effect, you can utilize the CSS transition property. Specifically, you can set a transition delay on mouseout while having no delay on hover.

During hover, the background will change instantly; however, when the mouse is moved away, the background transition will take a specified duration (e.g., 1 second, 1.25 seconds, or 2 seconds) to occur. If the user moves to another area before the transition completes, the background color will remain unchanged, fulfilling your desired outcome.

The key lies in implementing the following CSS directives:

span      {transition:background-color 0s ease-out 1s;} /* 1s delay on mouseout */
span:hover{transition:background-color 0s ease-out 0s;} /* No delay on hover */

div {
  width: 20%;
  margin: 0 auto;
  line-height: 2;
}

span {
  height: 2em;
  background: rgba(255, 255, 0, 0.2);
  vertical-align: middle;
  transition: background-color 0s ease-out 1s; /*  1s delay on mouseout */
}

span:hover {
  background: rgba(255, 0, 0, .5);
  transition: background-color 0s ease-out 0s; /*  No delay on hover */
}
<div>
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi hendrerit, enim eu fermentum condimentum, nulla tellus suscipit libero, quis tincidunt eros metus sed leo.</span> 
  <span>Suspendisse eu augue lectus.</span>
  <span>Sed aliquam pulvinar nibh eu vulputate. Sed venenatis eros at nisl ornare sollicitudin. Duis nec est gravida, sodales orci in, blandit magna.</span>            
  <span>Donec semper sodales lacus vel consequat.</span>
  <span>Mauris augue lectus, pretium eget dui interdum, iaculis dictum erat.</span>
  <span>Pellentesque sed nulla blandit, suscipit risus eu, malesuada justo.</span>
  <span>Fusce in dignissim magna. Quisque at tincidunt mauris.</span>
  <span>Fusce augue mauris, ornare eget lorem sed, bibendum lacinia justo.</span>
  <span>Nullam et vestibulum neque.</span>
  <span>Duis eget mauris elementum leo scelerisque dignissim accumsan tempor ex.</span>
  <span>Donec facilisis sollicitudin urna, sed efficitur ex ornare at.</span>      
  <span>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</span>
  <span>Duis at sem nibh. Sed sagittis velit sed ex tincidunt gravida facilisis eu augue.</span>
  <span>Aenean dapibus sem et dolor venenatis facilisis. Sed arcu tortor, luctus id felis quis, venenatis malesuada leo. Fusce vitae semper lacus.</span>
  <span>Phasellus magna eros, lobortis a faucibus a, elementum et sem. Nunc porta auctor arcu, eu viverra tellus vestibulum id. Morbi consequat sed magna id aliquam.</span>
  <span>Donec vehicula odio nec ullamcorper ornare.</span>
  <span> Vestibulum ut ultricies neque.</span>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you tell me which specific font Adobe Edge Code (Brackets) uses in its code editor?

Can someone please help me? I'm trying to identify the syntax highlighter being used in this code. Is it Prettify or something else? ...

Tips for switching back and forth with JQuery

I have an accordion element that opens on each click, but I am wondering how to close it back again? Here is an example of the HTML structure: <ul class="accordion"> <li id="one" class="files"> <a href="#one">Calendar 1<span& ...

When attempting to click the submit button, the action of submitting a form using jQuery/AJAX is not functioning as expected

When attempting to submit a form using jquery/AJAX, my function does not get called when clicking on the submit button. The structure of my website is as follows: CarMenu.php <html lang="en"> <html> <head> <meta charset="ISO-8859- ...

Show validation error messages for radio buttons alongside images in a single row

Within a div, I have placed three radio buttons with images inline. My goal is to show a validation message using bootstrap when the submit button is clicked and there is no user input. I attempted to add another div after the radio buttons with the class ...

What is the best way to animate a three.js object to the right using GSAP without obstructing the surrounding HTML text?

As a newcomer to web design, I seek forgiveness if my question appears basic. I am working on an animated object in three.js that I want to move to the left side of the screen using GSAP. Additionally, I have a text "Hello" on the left side of the screen. ...

The tabs in bootstrap appear to be functioning properly, but the data is not displaying as expected

Currently, I am incorporating Bootstrap into my project and I am attempting to include a Twitter Bootstrap tab. I have already added jQuery and bootstrap-tabs.js to my project. Below is the script that I have added: <script> $('#myTab a&apos ...

Vue component updating its model only upon input element losing focus

I'm a beginner with vue and I'm currently working on incorporating an ajax search feature that triggers when a keyup event occurs. I have noticed that the model only updates when the input element loses focus. Sample HTML Code: <input name=" ...

The row containing a list of inline elements cannot be cleared in Safari due to the ineffectiveness of the

I have encountered an issue with my list formatting that seems to work in Chrome and Firefox but not in Safari. The pseudo attribute is not taking effect in Safari and I am wondering if there is a workaround or a different approach that I should take. (Not ...

Issue with SVG marker not functioning properly when hovered over

I am having an issue with buttons containing SVG elements, here is an example code snippet: <button> Checkout <ArrowSvg /> </button> The ArrowSvg component looks like this (with the line having a class of "svg-line"): <svg fill=&quo ...

the failure of the second function to execute

Struggling with a particular issue. Two functions have been created as shown below: function limit_char_normal(textid, limit, infodiv){ var text = $('#'+textid).val(); var textlength = text.length; if (textlength > limit) { ...

Distance from the border

Having a small issue with margin, here is the code: echo '<p class="news_post">'; $stripped = strip_tags($post,'<img>'); $break = str_replace('>','><br>',$stripped); ...

Is there a solution to move my navbar that is frozen halfway on the screen?

I'm in the process of developing a website and have implemented a sticky navbar using CSS. However, I've noticed that when I scroll down, the navbar appears to be "stuck" slightly further down the page (as shown in the second image). Can anyone p ...

Choose the section of the date input that represents the day

Is there a way to focus an HTML input element with type="date" and select only the day part of the date? I attempted: $("#entry-date-text").focus(); var dt = $("#entry-date-text")[0]; dt.setSelectionRange(3, 5); However, this resulted in the following e ...

Morris bar adjusts size when printing

I'm facing an issue with printing my Morris bar chart results. Everything looks fine in HTML, but when I try to print it, the layout seems off. Here is what I have tried so far: <script> function myFunction() { window.print(); } </script ...

Unable to change Gutters to 0 in the .container-fluid class in Bootstrap 5.2

I have gone through all the answers related to my question, but I couldn't find a solution for it. Below is the HTML code with Bootstrap 5.2 that I am working on: <section id="title"> <div class="container-fluid"> ...

Creating a Dynamic Navigation Bar with HTML and CSS

I've been exploring the code on w3schools.com, and while there are some great examples, I'm struggling to understand it all. Unfortunately, there aren't any instructions on customizing the code for a third level of menus. Can someone simplif ...

Creating a unique SVG pattern starting from the center

I'm currently working on implementing a grid pattern that spans the entire viewport, following this solution. Although the grid starts from the top-left corner of the viewport, my goal is to have it start from the middle of the screen instead. This w ...

How to dynamically update the value of a TextBoxFor in asp.net MVC when a text box value changes

I need some assistance with a specific topic. In my scenario, I have two textboxes on my view. I want the value generated in my controller to be applied to textbox2 when there is a change in textbox1. For instance, if I enter a username in textbox1, textb ...

The issue with displaying Infogram embed code in a React application

Hi there, I'm having an issue with embedding a code from infogram into my react app. Here is the code snippet: <div class="infogram-embed" data-id="861ca70e-552c-4a4f-960a-4c7e7ff62881" data-type="interactive" data-title="Step by Step Charts">& ...

Position the Figcaption over the Image

Running a website, I am facing an issue with adding copyright information to the top-left corner of an image. The img element is set to float:left; and the figcaption appears after it. However, there are some complications: 1) Using the position:absolute ...