Home > Blockchain >  CSS Background Color for :before / :after independent of parent
CSS Background Color for :before / :after independent of parent

Time:12-15

I have a series of CSS rules to add FontAwesome icons before/after links for PDFs, phone numbers, email addresses, etc.

Additionally, I have a global hover rule for links, which makes the background color of the element yellow.

.main a:hover {
  background-color: yellow;
}

.main a[href^="tel"]:before {
  content: '\f879';
  background-color: transparent;
}

.main a[href^"tel"]:hover::before {
  background-color: transparent;
}
<div >
  <p><a href="tel:131313">131313</a></p>
</div>

My problem is that I don't want the yellow hover color to apply to the icons.

If I set the hover color on the pseudo-elements to a specific color (e.g., not transparent), everything is okay. But these links can appear anywhere (cards, accordions, etc.), which may have different background colors, so I'd rather not have to define every possible instance.

CodePudding user response:

You can give position: absolute styling to your pseudo-element. This will seperate it from its parent. Try the following:

.main a[href^="tel"] {
  content: '\f879';
  background-color: transparent;
  margin-left: 10px;
}

.main a[href^="tel"]:before {
  content: '\f879';
  background-color: transparent;
  position: absolute;
  left: 0;
}

Adjust the margin according to your liking!

CodePudding user response:

Here's my solution using jQuery to wrap with span all anchors that have attribute href starting with "tel". I don't have FontAwesome imported here so your icon does not display correctly, but you can see that your desired highlighting works even when the anchor is surrounded by paragraph text.

$(function() {
  $('a[href^="tel"]').html('<span>'   $('a[href^="tel"]').html()   '</span>');
});
.main a:before {
  content: '\f879A';
}
.main a span:hover {
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div >
  <p>Hello, <a href="tel:131313">131313</a>!</p>
</div>

CodePudding user response:

You can use a shifted gradient but you will need to update the value based on your case as it will depend on the size of the icon:

.main a:hover {
  background: linear-gradient(yellow 0 0) 10px no-repeat;
}

.main a[href^="tel"]:before {
  content: '\f879';
  background-color: transparent;
}

.main a[href^"tel"]:hover::before {
  background-color: transparent;
}
<div >
  <p><a href="tel:131313">131313</a></p>
</div>

  • Related