How to disable a link using only CSS?

前端 未结 22 2873
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 02:58

Is there any way to disable a link using CSS?

I have a class called current-page and want links with this class to be disabled so that no action occurs

22条回答
  •  借酒劲吻你
    2020-11-22 03:25

    If you want it to be CSS only, the disabling logic should be defined by CSS.

    To move the logic in the CSS definitions, you'll have to use attribute selectors. Here are some examples :

    Disable link that has an exact href: =

    You can choose to disable links that contain a specific href value like so :

    Exact path
    
    [href="//website.com/exact/path"]{
      pointer-events: none;
    }
    

    Disable a link that contains a piece of path: *=

    Here, any link containing /keyword/in path will be disabled

    Contains in path
    
    [href*="/keyword/"]{
      pointer-events: none;
    }
    

    Disable a link that begins with: ^=

    the [attribute^=value] operator target an attribute that starts with a specific value. Allows you to discard websites & root paths.

    Begins with path
    
    [href^="//website.com/begins/with"]{
      pointer-events: none;
    }
    

    You can even use it to disable non-https links. For example :

    a:not([href^="https://"]){
      pointer-events: none;
    }
    

    Disable a link that ends with: $=

    The [attribute$=value] operator target an attribute that ends with a specific value. It can be useful to discard file extensions.

    Link to pdf
    
    [href$=".pdf"]{
      pointer-events: none;
    }
    

    Or any other attribute

    Css can target any HTML attribute. Could be rel, target, data-customand so on...

    Blank link
    
    [target=_blank]{
      pointer-events: none;
    }
    

    Combining attribute selectors

    You can chain multiple rules. Let's say that you want to disable every external link, but not those pointing to your website :

    a[href*="//"]:not([href*="my-website.com"]) {
        pointer-events: none;
    }
    

    Or disable links to pdf files of a specific website :

    Link to image
    
    [href^="//website.com"][href$=".jpg"] {
      color: red;
    }
    

    Browser support

    Attributes selectors are supported since IE7. :not() selector since IE9.

提交回复
热议问题