Html 如何使用 CSS 使整个 div 可点击
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17354364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make an entire div clickable with CSS
提问by Emil Morris
Sometimes you want to make an entire div (or other element) into a clickable link. Here's an example.
有时您希望将整个 div(或其他元素)制作成一个可点击的链接。这是一个例子。
Here's a cross-browser way to do it using pure CSS:
这是使用纯 CSS 实现的跨浏览器方式:
HTML:
<div class="clickable">
<a href="URL_OF_LINK_TARGET"> </a>
Rest of div content goes here
</div>
CSS:
div.clickable { /* Containing div must have a position value */
position:relative;
}
div.clickable a {
position:absolute;
width:100%;
height:100%;
top:0;
left:0;
text-decoration:none; /* Makes sure the link doesn't get underlined */
z-index:10; /* raises anchor tag above everything else in div */
background-color:white; /*workaround to make clickable in IE */
opacity: 0; /*workaround to make clickable in IE */
filter: alpha(opacity=1); /*workaround to make clickable in IE */
}
First, give the containing div position. That way, when we apply “position:absolute;” to the link (see next paragraph) it will position itself relative to the containing div.
首先,给出包含 div 的位置。这样,当我们应用“position:absolute;”时 到链接(见下一段),它将相对于包含的 div 定位自己。
Next, make the link absolutely positioned and the full size and depth of the containing div. The link's z-index makes sure it's above everything else in the div, so no matter where you click, you're clicking the link.
接下来,使链接绝对定位并包含 div 的完整大小和深度。链接的 z-index 确保它高于 div 中的所有其他内容,因此无论您单击何处,都在单击该链接。
IE, naturally, has quirks. In this case, IE requires a background color for such a link to be clickable, so we give it a background color (white), set the opacity to 0, then give it an IE-only opacity of 1% using IE's proprietary filter property.
IE自然有怪癖。在这种情况下,IE 需要背景颜色才能使此类链接可点击,因此我们给它一个背景颜色(白色),将不透明度设置为 0,然后使用 IE 的专有过滤器属性为其提供 1% 的 IE-only 不透明度.
Finally, put whatever content you want in the div. If you're going to be layering the content using z-index, just make sure not to give any element a higher z-index than the link.
最后,把你想要的任何内容放在 div 中。如果您打算使用 z-index 对内容进行分层,请确保不要为任何元素提供比链接更高的 z-index。
回答by Michael Terry
You can wrap a div in a link and it is valid HTML5.
您可以将 div 包装在链接中,并且它是有效的 HTML5。
<a href="#">
<div></div>
</a>