插件窝 干货文章 如何使用CSS显示链接之后的URL

如何使用CSS显示链接之后的URL

after 链接 方法 href 52    来源:    2025-04-22

使用CSS显示链接之后的URL

在CSS中,你可以使用::after伪元素结合attr()函数来显示链接之后的URL。以下是几种实现方法:

方法一:基本实现

a::after {
  content: " (" attr(href) ")";
  font-size: 0.8em;
  color: #666;
}

方法二:只对特定链接显示

a.show-url::after {
  content: " → " attr(href);
  margin-left: 0.5em;
  color: #999;
}

方法三:打印样式表中使用

@media print {
  a::after {
    content: " (" attr(href) ")";
    font-size: 90%;
    color: #555;
  }
}

方法四:美化显示

a[href]::after {
  content: " [" attr(href) "]";
  font-family: monospace;
  font-size: 0.9em;
  opacity: 0.7;
  margin-left: 3px;
}

注意事项

  1. 对于长URL,可能会影响页面布局,可以添加以下样式限制宽度:

    a::after {
     max-width: 200px;
     display: inline-block;
     overflow: hidden;
     text-overflow: ellipsis;
     white-space: nowrap;
     vertical-align: bottom;
    }
    
  2. 如果想排除某些链接(如锚链接):

    a[href^="http"]::after,
    a[href^="//"]::after {
     content: " (" attr(href) ")";
    }
    
  3. 对于相对路径,可以使用JavaScript获取完整URL后通过data属性显示。

这些CSS方法可以让你在不修改HTML结构的情况下,优雅地显示链接后的URL地址。