Html 在 CSS 中实现 A HREF 的背景图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1044566/
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
Implementing background image for A HREF in CSS
提问by timbo
I have an href in HTML that I dynamically produce from a server. I have designed a nice rounded corner gif image that I would like to use as the background i.e. put the text (in white) over the gif image and have it still linkable.
我在 HTML 中有一个从服务器动态生成的 href。我设计了一个漂亮的圆角 gif 图像,我想将其用作背景,即将文本(白色)放在 gif 图像上并使其仍可链接。
The current html looks like:
当前的 html 看起来像:
<h2>
<!--img src="images/greenback.gif"-->
<a id="site-title0" class="titletext" href="#">
Alligator Creek, Bowling Green Bay National Park
</a>
</h2>
<div id="descrip0" class='description'>
20km S of Townsville. .85/night. Gates close...
What is the best way to do this with CSS? It seems I could either use relative positioning to move the text over the background image, but in early experiments, this affects the rest of the flow on the page.
用 CSS 做到这一点的最佳方法是什么?似乎我可以使用相对定位将文本移动到背景图像上,但在早期的实验中,这会影响页面上的其余流程。
Or, maybe using CSS background-image is the best way?
或者,也许使用 CSS background-image 是最好的方法?
回答by David says reinstate Monica
As Daniel says, really:
正如丹尼尔所说,真的:
a.particular-link {display: block; /* or inline-block; I think IE would respect it since a link is an inline-element */
background: #fff url(path/to/image.gif) top left no-repeat;
text-align: center;
line-height: 50px; } /* line height should be equal to the height of the image to vertically center using this technique */
I'd also -and this may simply be personal habit, affectation and received 'wisdom'- suggest using .png
rather than .gif
. But, as noted, it's likely a personal and subjective thing.
我也 - 这可能只是个人习惯,做作和获得“智慧” - 建议使用.png
而不是.gif
. 但是,如前所述,这可能是个人和主观的事情。
Answer edited in response to timbo's comment.
为回应 timbo 的评论而编辑的答案。
Also, and this ain't particularly pretty, there's a code demo here: http://davidrhysthomas.co.uk/so/a-img-bg.html
另外,这不是特别漂亮,这里有一个代码演示: http://davidrhysthomas.co.uk/so/a-img-bg.html
回答by Daniel A. White
You have to set the link to display: block
您必须将链接设置为 display: block
回答by Will Moore
display: block on the a or attach the background image to the h2. Either way, be sure to set a background color on the a or the h2 if you're using white text. If some one has CSS on and images off, they wont see your link. Means you may need to fill in the corners of your rounded corner image to the bg color of the page.
display: 在 a 上阻止或将背景图像附加到 h2。无论哪种方式,如果您使用白色文本,请务必在 a 或 h2 上设置背景颜色。如果有人打开 CSS 而关闭图像,他们将看不到您的链接。意味着您可能需要将圆角图像的角填充为页面的 bg 颜色。