CSS:宽度为“内联”的显示元素

时间:2010-08-03 16:48:46

标签: css

我有一个图标,我希望能够在任意点放入文本并使其“流动”文本。

背景:

<img>标记最适用于此。但是,我不想在任何地方都指定href。如果图标/位置发生变化,这将在未来出现问题。它还取决于我知道图像的路径,由于URL重写和同一页面的不同映射等,我不会总是知道。我想做<span class="icon"></span>之类的事情,并将我的图标作为background-image。当然,这不起作用,因为你不能在内联元素上有宽度。将它作为一个块(即。<div>)元素不起作用(出于显而易见的原因)并且浮动它也不起作用。 display: inline-block;适用于某些浏览器但不是全部。使用padding:填充正确的高度和宽度会在不同的浏览器中产生混合结果。使用带有<img>透明图片的href标记和背景图片 有效,但看起来很黑。

对于实现这一目标的最佳方法有什么想法?

2 个答案:

答案 0 :(得分:0)

您可以将<span class="icon"></span>绝对定位在您的链接中,如下所示:

<a href="">Some text <span class="icon"></span></a>

您可以在绝对定位的元素上指定宽度/高度,因此CSS看起来像这样:

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;
}

通过将<a>的位置设置为相对,它使其成为绝对定位的<span class="icon">的坐标系。

使用图标的图像标记

如果您不知道图标的显示位置,可以使用带有透明.gif格式的<img>标记作为其来源。

<p>Lorem ipsum <img src="clear.gif" alt="icon" class="icon" /> dolar velarium</p>

然后使用CSS background属性设置真实图标源:

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;
}

答案 1 :(得分:0)

这可能看起来有点黑客,但你可以background-imagefont-size一起使用,并用span填充足够的不间断空格来显示图片。

<span style="background-image:url('icon.gif'); width:200px; font-size: 36pt">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>

当然,它不会是你需要的确切尺寸,但有一点点,你可以找到合适的结果。