How to create an HTML button that acts like a link?
HTML buttons are used in various ways on the web page such as for hiding and showing any components, for submitting any task, and many more.
Sometimes HTML buttons can be used as a link for redirecting to some specific page. There are many ways through which we can create a button that acts as a link.
Using <button> tag within <a> tag
The simplest way to create the button which acts as a link is to wrap the <button> within the <a>.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
</head>
<body>
<a href="http://www.studytonight.com" target="_parent">
<button>Click me !</button>
</a>
</body>
</html>
Output
when you click on the button you will be redirected to the page.
Using <form> tag
Use the <form> tag and add the desired URL to the action attribute within <form>. Add <button> tag with type="submit" within the form.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
</head>
<body>
<h2> Button act as link using form</h2>
<form action="http://www.studytonight.com">
<button type="submit"> Go to </button>
</form>
</body>
</html>
Output
Here is the output of the above program.
Style the button as a link using CSS properties
We can also use CSS property to style the link to appears as a button. Include button class within tag <a>. Also use CSS property to add background color, padding, border, margin, etc to the button class.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
<style>
.button {
background-color: green;
border: none;
color: white;
padding: 10px 20px;
font-size: 25px;
text-align: center;
text-decoration: none;
display: inline-block;
margin: 4px 2px;
cursor: pointer;
}
</style>
</head>
<body>
<h2> Button as link using CSS </h2>
<a href="https://www.studytonight.com/" class="button">Click Here</a>
</body>
</html>
Output
Here is the output of the above program.
Using JavaScript
We can use onlick event attribute to buttons so that they act as links. Just click on the button and it will redirect to the specified URL.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
</head>
<body>
<h2> Button as link using Javascript </h2>
<button onclick="window.location.href='https://studytonight.com';">
Click Here
</button>
</body>
</html>
Output
Here is the output of the above program.
Conclusion
We have seen that there are several ways that can be used to create an HTML button that acts as a link.