¿Cómo puedo hacer que un enlace html parezca un botón?


Estoy usando ASP.NET, algunos de mis botones sólo hacen redirecciones. Preferiría que fueran enlaces ordinarios, pero no quiero que mis usuarios noten mucha diferencia en la apariencia. Consideré imágenes envueltas por anclas, es decir, etiquetas, pero no quiero tener que encender un editor de imágenes cada vez que cambio el texto en un botón.

 127
Author: feeela, 2009-04-02

18 answers

Aplicar esta clase a la misma

.button {
  font: bold 11px Arial;
  text-decoration: none;
  background-color: #EEEEEE;
  color: #333333;
  padding: 2px 6px 2px 6px;
  border-top: 1px solid #CCCCCC;
  border-right: 1px solid #333333;
  border-bottom: 1px solid #333333;
  border-left: 1px solid #CCCCCC;
}
<a href="#" class="button">Example</a>
 181
Author: TStamper,
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-01-16 16:11:07

Tan tonto como creo que es esto voy a publicar esta antigua pregunta.

¿Por qué no simplemente envolver una etiqueta de anclaje alrededor de un elemento de botón?

<a href="somepage.html"><button type="button">Text of Some Page</button></a>

Después de leer este post y probar la respuesta aceptada sin el resultado deseado que estaba buscando, probé lo anterior y obtuve exactamente lo que quería.

NOTA

Esto solo funcionará para IE9+, Chrome, Safari, Firefox y probablemente Opera.

 112
Author: guanome,
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
2013-07-19 12:14:25

En mi humilde opinión, hay una solución mejor y más elegante. Si su enlace es este:

<a href="http://www.example.com">Click me!!!</a>

El botón correspondiente debe ser este:

<form method="GET" action="http://www.example.com">
<input type="submit" value="Click me!!!">
</form>

Este enfoque es más simple porque utiliza elementos html simples, por lo que funcionará en todos los navegadores sin cambiar nada. Además, si tiene estilos para sus botones, esta solución aplicará los mismos estilos a su nuevo botón de forma gratuita.

 30
Author: Raul Luna,
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-07-21 11:28:34
a {
    display: block;
    height: 20px;
    width: auto;
    border: 1px solid #000;
}

Puedes jugar con etiquetas <a> como esta si les das una pantalla de bloque. Puede ajustar el borde para dar un efecto de sombra y el color de fondo para esa sensación de botón:)

 20
Author: Ólafur Waage,
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
2009-04-02 15:06:11

La propiedad CSS3 appearance proporciona una forma sencilla de estilizar cualquier elemento (incluido un ancla) con los estilos <button> integrados en un navegador:

a.btn {
  -webkit-appearance: button;
  -moz-appearance: button;
  appearance: button;
}
<body>
  <a class="btn">CSS Button</a>
</body>

CSS Tricks tiene un buen esquema con más detalles sobre esto. Tenga en cuenta que ninguna versión de Internet Explorer actualmente admite esto de acuerdo con caniuse.com.

 18
Author: Kevin Leary,
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-07-30 16:58:13

Si quieres un botón bonito con esquinas redondeadas, usa esta clase:

.link_button {
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
    border: solid 1px #20538D;
    text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.4);
    -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);
    -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);
    background: #4479BA;
    color: #FFF;
    padding: 8px 12px;
    text-decoration: none;
}
<a href="#" class="link_button">Example</a>
 15
Author: rupsray,
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-01-16 16:13:34

Como dijo TStamper, solo puedes aplicarle la clase CSS y diseñarla de esa manera. A medida que CSS mejora el número de cosas que puedes hacer con los enlaces se ha vuelto extraordinario, y ahora hay grupos de diseño que solo se centran en crear botones CSS de aspecto increíble para temas, y así sucesivamente.

Por ejemplo, puede hacer transiciones con background-color usando la propiedad-webkit-transition y pseduo-classes. Algunos de estos diseños pueden ser bastante locos, pero proporcionan una fantástica alternativa a lo que en el pasado se tuvo que haber hecho con, digamos, flash.

Por ejemplo (estos son alucinantes, en mi opinión), http://tympanus.net/Development/CreativeButtons / (esta es una serie de animaciones totalmente listas para usar para botones, con código fuente en la página de origen). http://www.commentredirect.com/make-awesome-flat-buttons-css / (en la misma línea, estos botones tienen efectos de transición agradables pero minimalistas, y hacen uso de nuevo estilo de diseño "plano".)

 3
Author: graemeboy,
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
2013-09-11 05:26:17

Puede crear un botón estándar, luego usarlo como imagen de fondo para un enlace. A continuación, puede establecer el texto en el enlace sin cambiar la imagen.

Las mejores soluciones si no tiene un botón renderizado especial son las dos ya dadas por TStamper y Waafur Waage.

 2
Author: cjk,
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
2009-04-02 15:09:18

Esto también entra en los detalles del css un poco más, y te da algunas imágenes:

Http://www.dynamicdrive.com/style/csslibrary/item/css_square_buttons /

 2
Author: GBa,
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
2009-04-02 15:10:06

Respuesta muy tardía:

He estado luchando con esto de vez en cuando desde que empecé a trabajar en ASP. Aquí está lo mejor que se me ha ocurrido:

Concepto: Creo un control personalizado que tiene una etiqueta. Luego en el botón puse un evento onclick que establece el documento.ubicación al valor deseado con JavaScript.

Llamé al control ButtonLink, para que pudiera confundirme fácilmente con LinkButton.

Aspx:

<%@ Control Language="VB" AutoEventWireup="false" CodeFile="ButtonLink.ascx.vb" Inherits="controls_ButtonLink" %>

<asp:Button runat="server" ID="button"/>

Código detrás:

Partial Class controls_ButtonLink
Inherits System.Web.UI.UserControl

Dim _url As String
Dim _confirm As String

Public Property NavigateUrl As String
    Get
        Return _url
    End Get
    Set(value As String)
        _url = value
        BuildJs()
    End Set
End Property
Public Property confirm As String
    Get
        Return _confirm
    End Get
    Set(value As String)
        _confirm = value
        BuildJs()
    End Set
End Property
Public Property Text As String
    Get
        Return button.Text
    End Get
    Set(value As String)
        button.Text = value
    End Set
End Property
Public Property enabled As Boolean
    Get
        Return button.Enabled
    End Get
    Set(value As Boolean)
        button.Enabled = value
    End Set
End Property
Public Property CssClass As String
    Get
        Return button.CssClass
    End Get
    Set(value As String)
        button.CssClass = value
    End Set
End Property

Sub BuildJs()
    ' This is a little kludgey in that if the user gives a url and a confirm message, we'll build the onclick string twice.
    ' But it's not that big a deal.
    If String.IsNullOrEmpty(_url) Then
        button.OnClientClick = Nothing
    ElseIf String.IsNullOrEmpty(_confirm) Then
        button.OnClientClick = String.Format("document.location='{0}';return false;", ResolveClientUrl(_url))
    Else
        button.OnClientClick = String.Format("if (confirm('{0}')) {{document.location='{1}';}} return false;", _confirm, ResolveClientUrl(_url))
    End If
End Sub
End Class

Ventajas de este esquema: Parece un control. Escribe una sola etiqueta para él,

El botón resultante es un botón HTML "real" y por lo tanto se parece a un botón real. Usted no tiene que tratar de simular el aspecto de un botón con CSS y luego luchar con diferentes miradas en diferentes navegadores.

Aunque las habilidades son limitadas, puedes ampliarlas fácilmente añadiendo más propiedades. Es probable que la mayoría las propiedades solo tendrían que" pasar por " al botón subyacente, como hice para text, enabled y cssclass.

Si alguien tiene una solución más simple, más limpia o mejor, me encantaría escucharla. Esto es un dolor, pero funciona.

 2
Author: Jay,
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-03-14 13:51:32

Puede hacerlo con JavaScript:

  1. Obtener estilos CSS de botón real con getComputedStyle(realButton).
  2. Aplica los estilos a todos tus enlaces.

/* javascript, after body is loaded */
'use strict';

{ // Namespace starts (to avoid polluting root namespace).
  
  const btnCssText = window.getComputedStyle(
    document.querySelector('.used-for-btn-css-class')
  ).cssText;
  document.querySelectorAll('.btn').forEach(
    (btn) => {
      
      const _d = btn.style.display; // Hidden buttons should stay hidden.
      btn.style.cssText = btnCssText;
      btn.style.display = _d;
      
    }
  );
  
} // Namespace ends.
<body>
  <h3>Button Styled Links</h3>
  <button class="used-for-btn-css-class" style="display: none"></button>
  <a href="//github.io" class="btn">first</a>
  <a href="//github.io" class="btn">second</a>
  <button>real button</button>
  <script>/* You may put JS here. */</script>
</body>
 2
Author: ilyaigpetrov,
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-02-01 13:58:48

Utilice esta clase. Hará que su enlace se vea igual que un botón cuando se aplique usando la clase button en una etiqueta a.

AQUÍ ESTÁ LA DEMO JSFIDDLE

O

AQUÍ HAY OTRA DEMO JSFIDDLE

.button {
    display: inline-block;
    outline: none;
    cursor: pointer;
    border: solid 1px #da7c0c;
    background: #478dad;
    text-align: center;
    text-decoration: none;
    font: 14px/100% Arial, Helvetica, sans-serif;
    padding: .5em 2em .55em;
    text-shadow: 0 1px 1px rgba(0,0,0,.3);
    -webkit-border-radius: .5em; 
    -moz-border-radius: .5em;
    border-radius: .3em;
    -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.2);
    -moz-box-shadow: 0 1px 2px rgba(0,0,0,.2);
    box-shadow: 0 1px 2px rgba(0,0,0,.2);
}
.button:hover {
    background: #f47c20;
    background: -webkit-gradient(linear, left top, left bottom, from(#f88e11), to(#f06015));
    background: -moz-linear-gradient(top,  #f88e11,  #f06015);
    filter:  progid:DXImageTransform.Microsoft.gradient(startColorstr='#f88e11', endColorstr='#f06015');
}
.button:active {
    position: relative;
    top: 1px;
}
 2
Author: Muhammad Ashikuzzaman,
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-07-29 07:13:15

¿Qué tal usar asp:LinkButton?

Puedes hacer eso - Hice que un linkbutton pareciera un botón estándar, usando la entrada de TStamper. Sin embargo, el subrayado se mostró debajo del texto cuando flotaba, a pesar de la configuración text-decoration: none.

Pude detener el hover-underlining agregando style="text-decoration: none" dentro del linkbutton:

<asp:LinkButton 
id="btnUpdate" 
CssClass="btnStyleTStamper" 
style="text-decoration: none" 
Text="Update Items"   
Onclick="UpdateGrid"  
runat="server"
/>
 2
Author: Christian,
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-07-30 07:12:06

Esto es lo que usé. El botón de enlace es

<div class="link-button"><a href="/">Example</a></div>

CSS

/* body is sans-serif */ 

.link-button {
    margin-top:15px;
    max-width:90px;
    background-color:#eee;
    border-color:#888888;
    color:#333;
    display:inline-block;
    vertical-align:middle;
    text-align:center;
    text-decoration:none;
    align-items:flex-start;
    cursor:default;
    -webkit-appearence: push-button;
    border-style: solid;
    border-width: 1px;
    border-radius: 5px;
    font-size: 1em;
    font-family: inherit;
    border-color: #000;
    padding-left: 5px;
    padding-right: 5px;
    width: 100%;
    min-height: 30px;
}

.link-button a {
    margin-top:4px;
    display:inline-block;
    text-decoration:none;
    color:#333;
}

.link-button:hover {
    background-color:#888;
}

.link-button:active {
    background-color:#333;
}

.link-button:hover a, .link-button:active a {
    color:#fff;
}
 1
Author: Andrew Howden,
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-08-22 05:58:14

Utilizo un asp:Button:

<asp:Button runat="server"
            OnClientClick="return location='targetPage', true;"
            UseSubmitBehavior="False"
            Text="Button Text Here"
/>

De esta manera, la operación del botón es completamente del lado del cliente y el botón actúa como un enlace a targetPage.

 1
Author: Manus Hand,
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-07-30 14:49:31

Esto funcionó para mí. Parece un botón y se comporta como un enlace. Puede marcarlo, por ejemplo.

<a href="mypage.aspx?param1=1" style="text-decoration:none;">
    <asp:Button PostBackUrl="mypage.aspx?param1=1" Text="my button-like link" runat="server" />
</a>
 0
Author: Andrej Adamenko,
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-07-10 18:43:48

.button {
  font: bold 11px Arial;
  text-decoration: none;
  background-color: #EEEEEE;
  color: #333333;
  padding: 2px 6px 2px 6px;
  border-top: 1px solid #CCCCCC;
  border-right: 1px solid #333333;
  border-bottom: 1px solid #333333;
  border-left: 1px solid #CCCCCC;
}
<a href="#" class="button">Example</a>
 0
Author: ,
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-02-28 18:23:43

¿Qué tal usar asp:LinkButton?

 -1
Author: Vladimir Kocjancic,
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-07-30 17:35:03