Home > Software design >  Detect two immediately adjacent links using only CSS
Detect two immediately adjacent links using only CSS

Time:10-31

TL;DR: how to style links (or any HTML element, for that matter) that are next to each other, with no other content in between?

Sometimes links can be placed next to each other, but enter image description here

Of course, the good practice of underlining links either permanently or on hover is sufficient to disambiguate the cases that are separated by whitespace, but there are cases where links are indeed immediately adjacent, likethis. This is less common, but I have come across it in the wild.

I am trying to define a user stylesheet to make these links immediately evident, and thought about using the adjacent sibling combinator to do this, e.g.:

a a { border-left: 1px solid red; }

This indeed is able to detect "glued" links like <a href="1"/><a href="2"/> (self-closing syntax used for conciseness) and whitespace-separated links like <a href="1"/> <a href="2"/>. However, it also captures links with text in between like <a href="1"/> foobar <a href="2"/>:

a a { border-left: 1px solid red; }
<ul>
  <li><a href="1">one</a><a href="2">two</a></li>
  <li><a href="1">one</a> <a href="2">two</a></li>
  <li><a href="1">one</a> foobar <a href="2">two</a></li>
</ul>

I have searched around but it seems to be impossible to differentiate the first and second cases above from the third, i.e. to style adjacent links only when there's no text content between them. Would there be any trick I'm missing that would allow such a functionality?

CodePudding user response:

By no means a full, general solution, but put here in case it helps towards something better.

In the first case scenario, and including no background-color being set, you can put a thin line before and after each anchor element.

Where they overlap they can be made black by mix-blend-mode: difference.

Otherwise they are not seen as they are white.

a::after,
a::before {
  content: '';
  width: 1px;
  height: 1em;
  background-color: white;
  position: absolute;
  mix-blend-mode: difference;
}
<ul>
  <li><a href="1">one</a><a href="2">two</a></li>
  <li><a href="1">one</a> <a href="2">two</a></li>
  <li><a href="1">one</a> foobar <a href="2">two</a></li>
</ul>

  • Related