Html 使 CSS 图像成为链接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19648693/
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
Make CSS Image a link
提问by user1172897
I'm just working on a site and I need an image in the top right corner that will link to another site when clicked. I created this in the CSS file:
我只是在一个网站上工作,我需要在右上角有一张图片,点击后可以链接到另一个网站。我在 CSS 文件中创建了这个:
div.image:before {
content:url(http://LinkToMyImage);
max-height: 169px;
max-width: 220px;
position: absolute;
top: 0px;
right: 0px;
}
Then add this html:
然后添加这个html:
<div class="image"></div>
It appears exactly how I want it but it's obviously not a link, is there a way I can make this linkable? I have tried href to the div but that does not work. Any help is greatly appreciated! Thanks!
它看起来正是我想要的,但它显然不是链接,有什么方法可以使这个链接?我已经尝试对 div 使用 href ,但这不起作用。任何帮助是极大的赞赏!谢谢!
采纳答案by Brandon
You can accomplish the exact same thing by simply using an anchor tag. Also, there's no need to be so specific with your css by referencing the element your class applies to. That will take quite a bit longer to process than just using the class name.
您可以通过简单地使用锚标记来完成完全相同的事情。此外,没有必要通过引用您的类适用的元素来对您的 css 进行如此具体的处理。与仅使用类名相比,这将花费更长的时间来处理。
If you need a higher level of specificity, target your element with another class name. Avoiding a specific element makes your code more flexible should the markup need to change in the future.
如果您需要更高级别的特异性,请使用另一个类名定位您的元素。如果标记需要在将来更改,避免使用特定元素会使您的代码更加灵活。
Change your html to:
将您的 html 更改为:
<a class="image"></a>
and your css to:
和你的 css 到:
.image:before {
content:url('http://LinkToMyImage');
// You should also be able to safely eliminate `display: block;`
// when setting `position: absolute`, but included it just in case you
// experienced problems setting width and height
display: block;
height: 169px;
width: 220px;
position: absolute;
// top 0 is usually inferred when setting position: absolute;
// you should be able to remove this
top: 0px;
right: 0px;
}