Replace <img> tag with font awesome icon from CSS

蓝咒 提交于 2019-12-07 11:45:21

问题


I have several hundreds of icons around a legacy application:

<img class="date-picker" src="/image/datepicker.png">

Following CSS removes the datepicker.png but the font awesome icon is not displayed

.date-picker {
    background-image: none;
}
.date-picker:after{
    font-family: FontAwesome;
    content: "\f073";
    color:grey;
    font-size:25px;
}

Is there a way how to achieve this without changing the IMG tags?


回答1:


Pseudo-elements only get applied to images whose src attributes fail to load. If the image successfully loads, the pseudo-element will not be used.

One thing you can do is apply this to the parent element, but this obviously depends on your markup:

div {
  height: 100px;
  width: 100px;
  position: relative;
}

div img {
  display: none;
}

div::after {
  content: 'foo';
  position: absolute;
  top: 0;
}
<div>
  <img src="http://placehold.it/100x100" />
</div>

Here we hide the img element and apply the pseudo-element to the div container, then absolutely-position the pseudo-element to sit inside (well, on top of) the div.




回答2:


You could wrap the image in a span and use the same class(es).

img.date-picker {
  display: none;
}
span.date-picker:after {
  font-family: FontAwesome;
  content: "\f073";
  color: grey;
  font-size: 25px;
  display: inline-block;
  margin: 1em;
  /* demo only */
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.css" rel="stylesheet" />
<span class="date-picker"><img class="date-picker" src="/image/datepicker.png"></span>



回答3:


Using jquery you can find all the img tag and wrap the img in a figure tag and apply the icon class to that.



来源:https://stackoverflow.com/questions/32757661/replace-img-tag-with-font-awesome-icon-from-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!