¿Cómo deshabilitar un enlace usando solo CSS?


¿Hay alguna forma de deshabilitar un enlace usando CSS?

Tengo una clase llamada current-page y quiero que los enlaces con esta clase estén deshabilitados para que no ocurra ninguna acción cuando se haga clic en ellos.

 761
Author: slick, 2010-01-19

20 answers

La respuesta ya está en los comentarios de la pregunta. Para mayor visibilidad, estoy copiando esta solución aquí:

.not-active {
  pointer-events: none;
  cursor: default;
  text-decoration: none;
  color: black;
}
<a href="link.html" class="not-active">Link</a>

Para el soporte del navegador, consulte https://caniuse.com/#feat=pointer-events. Si necesita soporte IE, hay una solución alternativa; consulte esta respuesta.

Advertencia: El uso de pointer-events en CSS para elementos no SVG es experimental. La característica solía ser parte de la especificación de borrador de interfaz de usuario CSS3, pero, debido para muchas cuestiones abiertas, se ha pospuesto a CSS4.

 1228
Author: RSK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-15 14:36:07

.disabled {
  pointer-events: none;
  cursor: default;
  opacity: 0.6;
}
<a href="#" class="disabled">link</a>
 123
Author: amir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-15 14:36:31

CSS solo se puede usar para cambiar el estilo de algo. Lo mejor que podrías hacer con CSS puro es ocultar el enlace por completo.

Lo que realmente necesita es algo de javascript. Así es como harías lo que quieres usando la biblioteca jQuery.

$('a.current-page').click(function() { return false; });
 119
Author: nickf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-19 05:01:27

CSS no puede hacer eso. CSS es solo para presentación. Sus opciones son:

  • No incluya el atributo href en sus etiquetas <a>.
  • Use JavaScript, para encontrar los elementos de anclaje con ese class, y elimine sus atributos href o onclick en consecuencia. jQuery te ayudaría con eso (NickF mostró cómo hacer algo similar pero mejor).
 32
Author: Kevin Conner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-19 05:13:56

Bootstrap Disabled Link

<a href="#" class="btn btn-primary btn-lg disabled" role="button">Primary link</a>

<a href="#" class="btn btn-default btn-lg disabled" role="button">Link</a>

Bootstrap Botón desactivado pero parece link

<button type="button" class="btn btn-link">Link</button>
 28
Author: Jigar Bhatt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-15 14:44:38

Puede establecer href atributo a javascript:void(0)

.disabled {
  /* Disabled link style */
  color: black;
}
<a class="disabled" href="javascript:void(0)">LINK</a>
 19
Author: Xinus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-15 14:45:38

Si desea atenerse solo a HTML/CSS en un formulario, otra opción es usar un botón. Dale estilo y establece el atributo disabled.

E. g. http://jsfiddle.net/cFTxH/1 /

 10
Author: Sebastian Patten,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-27 18:05:26

La única manera de hacer esto sin CSS sería establecer un CSS en un div de envoltura que haga que su a desaparezca y algo más tome su lugar.

EG:

<div class="disabled">
    <a class="toggleLink" href="wherever">blah</a>
    <span class="toggleLink">blah</span
</div>

Con un CSS como

.disabled a.toggleLink { display: none; }
span.toggleLink { display: none; }
.disabled span.toggleLink { display: inline; }

Para desactivar realmente la A tendrás que reemplazar su evento de clic o href, como han descrito otros.

PD: Solo para aclarar, consideraría esto una solución bastante desordenada, y para SEO tampoco es la mejor, pero creo que es la mejor con CSS puramente.

 10
Author: fyjham,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-15 14:46:21

Prueba esto:

<style>
.btn-disable {
    display:inline-block;
    pointer-events: none;       
}
</style>
 9
Author: Benk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-26 05:05:15

Si desea que sea solo CSS, la lógica de desactivación debe ser definida por CSS.

Para mover la lógica en las definiciones CSS, tendrás que usar selectores de atributos. Estos son algunos ejemplos :

Desactivar el enlace que tiene un href exacto: =

Puede optar por deshabilitar los enlaces que contienen un valor href específico de la siguiente manera:

<a href="//website.com/exact/path">Exact path</a>

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

Deshabilita un enlace que contenga una parte de la ruta: *=

Aquí, cualquier enlace que contenga /keyword/ en path será disabled

<a href="//website.com/keyword/in/path">Contains in path</a>

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

Deshabilita un enlace que comience con: ^=

El operador [attribute^=value] apunta a un atributo que comienza con un valor específico. Le permite descartar sitios web y rutas de raíz.

<a href="//website.com/begins/with/path">Begins with path</a>

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

Incluso puede usarlo para deshabilitar enlaces no https. Por ejemplo :

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

Desactivar un enlace que termina con: $=

El operador [attribute$=value] apunta a un atributo que termina con un valor específico. Puede ser útil descartar extensiones de archivo.

<a href="/path/to/file.pdf">Link to pdf</a>

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

O cualquier otro atributo

Css puede apuntar a cualquier atributo HTML. Podría ser rel, target, data-customy así sucesivamente...

<a href="#" target="_blank">Blank link</a>

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

Combinando selectores de atributos

, puede encadenar varias reglas. Digamos que desea desactivar todos los enlaces externos, pero no los que apuntan a su sitio web :

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

O desactivar enlaces a archivos pdf de un sitio web específico:

<a href="//website.com/path/to/file.jpg">Link to image</a>

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

Soporte del navegador

Los selectores de atributos son soportados desde IE7. :not() selector desde IE9.

 9
Author: Creaforge,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-18 20:13:29

La propiedad pointer-events permite controlar cómo funcionan los elementos HTML responder a eventos de mouse / touch - incluyendo CSS hover / active states, haga clic/toque eventos en Javascript, y si el cursor es visible.

Esa es no la única forma en que deshabilita un enlace , sino una buena forma CSS que funciona en IE10+ y todos los navegadores nuevos:

.current-page {
  pointer-events: none;
  color: grey;
}
<a href="#" class="current-page">This link is disabled</a>
 7
Author: Alireza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-21 11:29:55

Busqué en Internet y no encontré nada mejor que este. Básicamente para desactivar la funcionalidad de clic en el botón, simplemente agregue el estilo CSS usando jQuery de la siguiente manera:

$("#myLink").css({ 'pointer-events': 'none' });

Entonces para habilitarlo de nuevo haga esto

$("#myLink").css({ 'pointer-events': '' });

Comprobado en Firefox e IE 11, funcionó.

 5
Author: Faisal Mq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-21 07:58:13

Gracias a todos los que publicaron soluciones, combiné múltiples enfoques para proporcionar una funcionalidad disabled más avanzada. Aquí hay una síntesis, y el código está a continuación.

This provides for multiple levels of defense so that Anchors marked as disable actually behave as such.
Using this approach, you get an anchor that you cannot:
  - click
  - tab to and hit return
  - tabbing to it will move focus to the next focusable element
  - it is aware if the anchor is subsequently enabled


1.  Include this css, as it is the first line of defense.  This assumes the selector you use is 'a.disabled'
    a.disabled {
      pointer-events: none;
      cursor: default;
    }

 2. Next, instantiate this class such as (with optional selector):
    $ ->
      new AnchorDisabler()

Aquí está la clase coffescript:

class AnchorDisabler
  constructor: (selector = 'a.disabled') ->
    $(selector).click(@onClick).keyup(@onKeyup).focus(@onFocus)

  isStillDisabled: (ev) =>
    ### since disabled can be a class or an attribute, and it can be dynamically removed, always recheck on a watched event ###
    target = $(ev.target)
    return true if target.hasClass('disabled')
    return true if target.attr('disabled') is 'disabled'
    return false

  onFocus: (ev) =>
    ### if an attempt is made to focus on a disabled element, just move it along to the next focusable one. ###
    return unless @isStillDisabled(ev)

    focusables = $(':focusable')
    return unless focusables

    current = focusables.index(ev.target)
    next = (if focusables.eq(current + 1).length then focusables.eq(current + 1) else focusables.eq(0))

    next.focus() if next


  onClick: (ev) =>
    # disabled could be dynamically removed
    return unless @isStillDisabled(ev)

    ev.preventDefault()
    return false

  onKeyup: (ev) =>

    # 13 is the js key code for Enter, we are only interested in disabling that so get out fast
    code = ev.keyCode or ev.which
    return unless code is 13

    # disabled could be dynamically removed
    return unless @isStillDisabled(ev)

    ev.preventDefault()
    return false
 3
Author: kross,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-16 20:53:25

Puedes usar este css:

a.button,button {
    display: inline-block;
    padding: 6px 15px;
    margin: 5px;
    line-height: 1.42857143;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    -ms-touch-action: manipulation;
    touch-action: manipulation;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    background-image: none;
    border: 1px solid rgba(0, 0, 0, 0);
    border-radius: 4px;
    -moz-box-shadow: inset 0 3px 20px 0 #cdcdcd;
    -webkit-box-shadow: inset 0 3px 20px 0 #cdcdcd;
    box-shadow: inset 0 3px 20px 0 #cdcdcd;
}

a[disabled].button,button[disabled] {
    cursor: not-allowed;
    opacity: 0.4;
    pointer-events: none;
    -webkit-touch-callout: none;
}

a.button:active:not([disabled]),button:active:not([disabled]) {
    background-color: transparent !important;
    color: #2a2a2a !important;
    outline: 0;
    -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .5);
    box-shadow: inset 0 3px 5px rgba(0, 0, 0, .5);
}
<button disabled="disabled">disabled!</button>
<button>click me!</button>
<a href="http://royansoft.com" disabled="disabled" class="button">test</a>
<a href="http://royansoft.com" class="button">test2</a>
 3
Author: javad shariaty,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-15 07:28:24

Demo aquí
Prueba este

$('html').on('click', 'a.Link', function(event){
    event.preventDefault();
});
 2
Author: Suresh Pattu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-09 12:40:07

También puede dimensionar otro elemento para que cubra los enlaces (usando el índice z derecho): Eso "comerá" los clics.

(Descubrimos esto por accidente porque tuvimos un problema con enlaces repentinamente inactivos debido al diseño "responsivo" que causó que un H2 los cubriera cuando la ventana del navegador era del tamaño de un móvil.)

 1
Author: Tor Iver Wilhelmsen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-01 06:59:08

He utilizado:

.current-page a:hover {
pointer-events: none !important;
}

Y no fue suficiente; en algunos navegadores todavía se muestra el enlace, parpadeando.

Tuve que añadir:

.current-page a {
cursor: text !important;
}
 1
Author: Pablo Molina,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-19 11:42:56

Es posible hacerlo en CSS

.disabled{
  cursor:default;
  pointer-events:none;
  text-decoration:none;
  color:black;
}
<a href="https://www.google.com" target="_blank" class="disabled">Google</a>

Ver en:

Tenga en cuenta que el text-decoration: none; y color: black; no es necesario, pero hace que el enlace se vea más como texto sin formato.

 0
Author: Judah rogan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-18 19:16:02

pointer-events:none desactivará el enlace:

.disabled {
       pointer-events:none;
}
<a href="#" class="disabled">link</a>
 0
Author: Nikki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-20 06:11:51

<a href="#!">1) Link With Non-directed url</a><br><br>

<a href="#!" disabled >2) Link With with disable url</a><br><br>
 0
Author: Rudra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-22 13:49:26