CSS:好玩的‘伪类’系列之——(:target)

:target

定义:指一个唯一的页面元素(目标元素),其id与当前URL片段匹配。一般结合锚点链接使用

触发条件:当当前页面存在被指定的目标元素时,可修改目标元素的样式

兼容:IE8及8以下不支持、Opera9.5以下不支持

举个栗子

html代码:

  <div style='width:50%;margin:0 auto'>
    <h3>目录</h3>
    <ol>
     <li><a href="#p1">跳到第一段!</a></li>
     <li><a href="#p2">跳到第二段!</a></li>
     <li><a href="#nowhere">因为目标不存在,所以这个链接毫无用处。</a></li>
    </ol>

    <h3>我的文章</h3>
    <p id="p1">点击上面第一个链接,可以跳转到我 <i>这里</i></p>
    <p id="p2">点击上面第二个链接,同样也可以跳转到我 <i>这里。</i>爽不爽?</p>
  </div>

css代码:

p:target {
  background-color: gold;
}

/* 在目标元素中增加一个伪元素*/
p:target::before {
  font: 70% sans-serif;
  content: "►";
  color: limegreen;
  margin-right: .25em;
}

/*在目标元素中使用italic样式*/
p:target i {
  color: red;
}

效果图:

CSS:好玩的‘伪类’系列之——(:target)

再看一个效果(用:target模拟一个全局弹窗的效果):

效果图:

CSS:好玩的‘伪类’系列之——(:target)

html代码:

  <ul>
    <li><a href="#example1">实例1</a></li>
    <li><a href="#example2">实例2</a></li>
  </ul>

  <div class="lightbox" id="example1">
    <figure>
      <a href="#" class="close"></a>
      <figcaption>我是一个全局的弹窗提示,之前被隐藏了,点击链接'实例1',你就可以看到我了</figcaption>
    </figure>
  </div>

  <div class="lightbox" id="example2">
    <figure>
      <a href="#" class="close"></a>
      <figcaption>我是也是一个全局的弹窗提示,之前被隐藏了,点击链接'实例2',你就可以看到我了</figcaption>
    </figure>
  </div>

css代码:

.lightbox {
  display: none;
}

/* Opened lightbox */
.lightbox:target {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* Lightbox content */
.lightbox figcaption {
  width: 25rem;
  position: relative;
  padding: 1.5em;
  background-color: lightpink;
}

/* Close button */
.lightbox .close {
  position: relative;
  display: block;
}

.lightbox .close::after {
  right: -1rem;
  top: -1rem;
  width: 2rem;
  height: 2rem;
  position: absolute;
  display: flex;
  z-index: 1;
  align-items: center;
  justify-content: center;
  background-color: black;
  border-radius: 50%;
  color: white;
  content: "×";
  cursor: pointer;
}

/* Lightbox overlay */
.lightbox .close::before {
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  position: fixed;
  background-color: rgba(0,0,0,.7);
  content: "";
  cursor: default;
}