CSS: Display element with width "inline"
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 an开发者_StackOverflow中文版d 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:
<a href="">Some text <span class="icon"></span></a>
You can specify width/height on absolutely positioned elements, so the CSS would look something like this:
a {
position: relative;
padding-right: 30px; /* width of your icon, assuming you're placing to the right of the text */
}
a .icon {
display: block; /* for good measure, but won't be required in all browsers */
position: absolute;
top: 0;
right: 0;
width: 30px;
height: 30px;
background: url(your-icon.png) no-repeat 0 0;
}
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.
<p>Lorem ipsum <img src="clear.gif" alt="icon" class="icon" /> dolar velarium</p>
Then set the real icon source using the CSS background property:
img.icon {
height: 30px;
width: 30px;
background: url(true-icon-src.png) no-repeat 0 0;
/* Use the following if you want to adjust the image's vertical position */
position: relative;
top: 5px;
}
This may seem a little hack-ish, but you could use background-image
with font-size
and pad your span
with enough non-breaking spaces to show the image.
<span style="background-image:url('icon.gif'); width:200px; font-size: 36pt"> </span>
Granted it won't be the exact size you'll need, but with a little finessing, you could find a suitable result.
精彩评论