简体   繁体   English

使用前面的元素居中CSS背景图像?

[英]Centering CSS background-image with preceeding elements?

http://jsfiddle.net/ksHuz/ http://jsfiddle.net/ksHuz/

I'm trying to use a background-image with the <a> element in this fiddle, but the image only center aligns with text in IE. 我正在尝试在提琴小提琴中使用<a>元素作为背景图像,但是图像仅与IE中的文本居中对齐。 How do I center align the image in all browsers? 如何在所有浏览器中居中对齐图像?

HTML: HTML:

<table>
    <tr>
        <td>
           <select>
               <option>1</option>
                              <option>33</option>
                              <option>c</option>
                              <option>a</option>
                              <option>aaef</option>
            </select> 
            text
            <a href="#"></a>
        </td>
    </tr>
</table>

CSS: CSS:

a{
 background-image: url(http://stefankendall.com/files/excel.png);   
    width: 16px;
    height: 16px;
    display: inline-block;
}

Adding vertical-align: middle; 添加vertical-align: middle; to the css for the anchor element will center it for standards-based browsers. 对于锚元素的CSS,它将以基于标准的浏览器为中心。 You might have to use some hack like those found on this page to get it to work in IE6 and IE7: http://foohack.com/2007/11/cross-browser-support-for-inline-block-styling/ 您可能必须使用此页面上的一些技巧才能使其在IE6和IE7中正常工作: http : //foohack.com/2007/11/cross-browser-support-for-inline-block-styling/

Edit: Come to think of it, you should probably use an actual image, in which case you could use a img { vertical-align: middle; } 编辑:想想看,你应该使用一个实际的图像,在这种情况下你可以使用a img { vertical-align: middle; } a img { vertical-align: middle; } for the same effect (and it should work cross-browser, since img is already inline-block). a img { vertical-align: middle; }为相同的效果(它应该工作跨浏览器,由于IMG是已内联块)。 Background images should ideally be used only for ornamentation, and a button is actual content. 理想情况下,背景图像仅用于装饰,按钮是实际内容。 For example, what if someone doesn't have css enabled? 例如,如果某人没有启用css怎么办? Image tags allow alt attributes, too, for accessibility. 图像标记也允许alt属性用于可访问性。

I think you need to re-think the approach. 我认为您需要重新考虑该方法。 Your background image is rendering fine inside the <a> but this element is separate from text inside the <td> . 您的背景图像在<a>内部呈现良好,但是此元素与<td>内部的文本分开。

Depending what exactly you're trying to achieve, you could put the text and the link inside a <span> for example, or put the text inside the <a> and style it to not look like a link. 根据您要实现的目标,您可以将文本和链接放在<span>中,或者将文本放在<a>并将其设置为看起来不像链接。 You can also position the two on top of each other using positioning and/or floats. 您还可以使用定位和/或浮动将两者放在彼此的顶部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM