I have an icon that I would like to be able to drop into text at arbitrary points and have it “flow” with the text.
Background:
An <img> tag works best for this. However, I don’t want to have to specify the href everywhere. That will present problems in the future should the icon/location change. It also depends on me knowing the path to the image which I won’t always know due to URL-rewrites and different mappings to the same page, etc. I would like to do something like <span class="icon"></span> and have my icon as the background-image. Of course, this doesn’t work since you can’t have width on an inline element. Having it as a block (ie. <div>) element doesn’t work (for obvious reasons) and floating it doesn’t work either. display: inline-block; works in some browsers but not all. Using padding: to pad-out the correct height and width gives mixed results in different browsers. Using an <img> tag with a transparent image for the href and a background-image
works but seems hacky.
Any thoughts on what the best way to accomplish this would be?
You could make the
<span class="icon"></span>absolutely positioned within your link like so:You can specify width/height on absolutely positioned elements, so the CSS would look something like this:
By setting the
<a>‘s postion to relative, it makes it the coordinate system for the absolutely positioned<span class="icon">.Using an Image Tag for the Icon
If you don’t know where the icon will appear, you can use an
<img>tag with a transparent .gif as its source.Then set the real icon source using the CSS background property: