I have written a web page in which links are all contained within their own tags. I've also made them all button styles with CSS (border, background color, padding). How do I enable the whole DIV to be clicked to activate the link?
By adding key handling, a tab index, a role and an aria-label, this div essentially becomes an accessible button and then we can add whatever content we want within the button. This solution works great for simple components that actually look and function like a button.
To display or hide a <div> by a <button> click, you can add the onclick event listener to the <button> element. The onclick listener for the button will have a function that will change the display attribute of the <div> from the default value (which is block ) to none .
You can't make the div a link itself, but you can make an <a> tag act as a block , the same behaviour a <div> has. You can then set the width and height on it. However, this doesn't make a 'div' into a link. It makes a link into a block element.
By prepending your href with # , you can target an HTML element with a specific id attribute. For example, <a href="#footer"> will navigate to the <div id="footer"> within the same HTML document. This type of href is often used to navigate back to the top of the page.
The best way to do this kind of effect (making links act like buttons) is to apply css to the links themselves. Here's a basic example:
a.mylink {
display: block;
padding: 10px;
width: 200px;
background-color: #000;
color: #fff;
}
Test it out - the whole of the button is clickable. And it respects the browser's normal link actions like right-clicking, status url information, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With