从CSS而不是HTML中选择图像

时间:2014-08-16 22:28:14

标签: html css

我有一个棘手的问题。对这里的一些人来说可能很有趣。

我正在尝试克服html img并通过css background属性使用image。

所以,代码很简单:

<a id="logo" href="/"><img src="/logo1.png"></a>

CSS

position: relative;
height: 85px;
width: 200px;
background: url(/logo2.png) no-repeat;
background-size: 200px 200px;

所以,我希望html中的logo1被移除,而css image logo2超越了logo1。

注意:没有额外的div和类,只有那个html标记!

尝试了一切,但我认为这是不可能的?

2 个答案:

答案 0 :(得分:2)

使用display: none删除img并使用display: block/inline-block/table-cell获取您的身高和宽度。

在此示例中,正在删除红色<img>并替换为黄色CSS背景图像。

Example!

HTML

<a id="logo" href="/"><img src="http://www.placehold.it/200/FF0000"></a>

CSS

a { 
   position: relative;
   height: 85px;
   width: 200px;
   background: url(http://www.placehold.it/200/FFFF00) no-repeat;
   background-size: 200px 200px;
   display: block;
}
a img {
    display: none;
}

答案 1 :(得分:0)

如果要隐藏img标记并将其替换为背景图像。使用z-index并删除position:relative;从链接并将其应用于img。添加显示:块;到链接并给它固定的尺寸。

<强> HTML

<h2>Your actual code:</h2>
<a id="logo2" href="/"><img src="http://www.placehold.it/100x100" /></a>
<br> 
<h2>You want to hide the img tag and replace it with the background image. Use z-index and replace position:relative; and apply it to the img instead.</h2>
<a id="logo" href="/"><img src="http://www.placehold.it/100x100" /></a>

<强> CSS

    #logo, #logo2{
        height: 100px;
        width: 200px;
        display:block;
        background: url(http://www.placehold.it/100x100) no-repeat;
        background-size: 200px 100px;
        z-index:2;
    }
    #logo img{
        z-index:-1;position:relative;
    }

DEMO http://jsfiddle.net/a_incarnati/stkrj9eq/

如果你想隐藏img,你可以使用几种技术,也可以使用不透明度,visibility:hidden,display:none;取决于你想要实现的目标。