skip to Main Content

I want to make targets of the :target pseudo-class visible. That is, if the target is a block element, e.g. <p>, that <p> should be outlined; and if the target is an inline element, e.g. <span>, that <span> should be outlined; and if the target is an empty <a> element, there should be a horizontal line.

:target:not(a:target) {
  outline: red dashed 1px;
}

a:target::before {
  content: '';
  display: block;
  border-top: red dashed 1px;
}
<p><a href="#empty-a">empty a</a></p>
<p><a href="#p">p</a></p>
<p><a href="#span">span</a></p>
<p>...</p>
<a id="empty-a"></a>
<p id="p">this is <span id="span">the</span> target</p>

This example works, but there is a problem: a target that is a regular, non-empty <a> element will have a line on tp of it, not an outline, and this breaks consistency.

:target:not(a:target) {
  outline: red dashed 1px;
}

a:target::before {
  content: '';
  display: block;
  border-top: red dashed 1px;
}
<p><a href="#nonempty-a">non-empty a</a></p>
<p>...</p>
<p>this is <a href="#" id="nonempty-a">the</a> target</p>

Could anybody help to fix it?


Edit

Question: Why using an empty link to start with? – Temani Afif

Answer: This is a technique (that I borrowed from Apple) that allows to target single place using multiple #-links. For example

<p><a href="yellow">yellow</a></p>
<p><a href="hot">hot</a></p>
<p>...</p>
<a id="yellow"></a>
<a id="hot"></a>
<h1>Sun</h1>

2

Answers


  1. Chosen as BEST ANSWER

    As answered by Paulie_D in comments, this can be solved using the :empty pseudo-class:

    :target:not(empty) {
      outline: red dashed 1px;
    }
    
    :target:empty::before {
      border-top: red dashed 1px;
      content: '';
      display: block;
    }
    <p><a href="#emptya">empty a</a></p>
    <p><a href="#nonemptya">non-empty a</a></p>
    <p><a href="#p">p</a></p>
    <p><a href="#span">span</a></p>
    <p>...</p>
    <a id="emptya"></a>
    <p id="p">this <span id="span">is</span> <a href="#" id="nonemptya">the</a> target</p>


  2. I would use hr elements instead of links and it will work fine with one CSS rule

    :target {
      outline: red dashed 1px;
    }
    
    
    hr[id] {
      margin: 0;
      border: none;
    }
    <p><a href="#empty-a">empty a</a></p>
    <p><a href="#empty-a">empty b</a></p>
    <p><a href="#p">p</a></p>
    <p><a href="#span">span</a></p>
    <p>...</p>
    <hr id="empty-a">
    <hr id="empty-b">
    <p id="p">this is <span id="span">the</span> target</p>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search