Paolo Montalto
Paolo Montalto

Reputation: 103

How to have a clickable button

I have a text link as "Click Me To Get There" that I transformed into a button via CSS.

This is what I used successfully:

.product-buttons-container {
  background-color: #ff6347;
  padding: 11px 24px;
  line-height: 17px;
  border-radius: 35px;
  cursor: pointer;
  text-align: center;
}

.product-buttons-container:hover {
  background-color: #E5423A;
}
<a href="#" class="product-buttons-container">Click Me To Get There</a>

The problem with that is that only the text still has the "a" tag with the destination URL. The area of the button is just look-and-feel and, although on mouse-hover the cursor change as pointer there is no link in the button padding.

What am I missing in order to get a fully clickable button?

Upvotes: 0

Views: 1255

Answers (1)

F. M&#252;ller
F. M&#252;ller

Reputation: 4062

The <a> tag has display: inline as default. You can make it display: inline-block or display: block to adjust the size of the element. As user Terry already pointed out, you can use cursor: pointer to style the cursor (it won't be necessary though if you use an <a> tag.)

You can either:

Style the <a> itself like a button

.button-link {
  padding: 10px;
  border-radius: 10px;
  background: silver;
  text-decoration: none;
  color: black;
}
<a href="https://www.google.com" class="button-link">I can be a button, too</a>

Wrap the <button> with a link element

.button-link {
  background-color: silver;
}

button {
  border: none;
  padding: 10px;
  border-radius: 10px;
  cursor: pointer;
}
<a href="https://www.google.com" class="button-link"><button>I am clickable</button></a>

Use <button> with JS and onclick (not recommended)

document.body.onload = function() {
  let buttons = document.querySelectorAll('[data-link]');
  for (let i = 0; i < buttons.length; i++) {
    let button = buttons[i];
    button.onclick = function() {
      window.location.href = button.dataset.link;
    }
  }
}();
.button {
  padding: 10px;
  border: none;
  border-radius: 10px;
  background-color: silver;
  cursor: pointer;
}
<button class="button" data-link="https://www.google.com">I am a link, too</button>

You don't even have to use <a> or <button> you could link whatever element you like. You can always add a link with the onclick attribute in javascript.

Here is a link in a bigger context:

.button {
  display: inline-block;
  margin: 0 20px;
  width: 100px;
  padding: 10px;
  border: 2px solid #333;
  border-radius: 10px;
  background-color: silver;
  color: #000;
  text-decoration: none;
}

.button:hover {
  background-color: #eaeaea;
}
<p>This represents some text on a website la-di-da
  <a class="button" href="#">this whole box shall be linked and act like a button</a> and after the link it just goes on ...
</p>
<p>Some other paragraph</p>

Upvotes: 2

Related Questions