我有 wordpress 侧边栏:
<h3 class="widget-title">TITLE OF SIDEBAR</h3>
我需要在“侧边栏的标题”之前显示小图标。我可以使用 CSS 吗?
或者我必须手动将图像添加到代码中?喜欢:
<h3 class="widget-title"><img src="">TITLE OF SIDEBAR</h3>
伪元素会做你想做的事。使用:before
伪元素,您的 CSS 将如下所示:
h3.widget-title:before {
content: url('/path/to/image');
}
这将在 的文本内容之前放置一个图像<h3>
,但是这根本不会改变 DOM,这一点很重要。
可以在 CSS Tricks 上找到关于伪元素如何工作的一个很好的解释。
如果你的图片是 10px 宽,你可以试试这个:
.widget-title {
background: url(smallicon.png) left top no-repeat;
padding-left: 10px;
}
保留您的 h3 标签而不包括 img 标签,并执行以下操作:
h3.widget-title {
position: relative;
padding-left: <width of the icon image>;
}
h3.widget-title:before {
content: '';
width: <width value>;
height: <height value>;
position: absolute;
left: 0;
display: block;
background: url(<path of the icon image>) no-repeat;
}
.widget-title:before {
content: url(path/to/image.png);
}
您可以在https://developer.mozilla.org/en-US/docs/Web/CSS/content找到更多信息。
h3:before {
content: url('https://www.google.com/images/srpr/logo4w.png')
}
是的,你可以在 CSS 中做到这一点。
只需使用:before
伪选择器,如下所示:
widget-title:before {
content:url('imagename.png');
}
或者,当然,使用h3:before { ... }
它来应用于所有h3
元素。
浏览器兼容性:这适用于所有常见浏览器,IE7 或更早版本除外。
为什么不简单地将图像应用为背景?
.widget-title {
background: url(...) no-repeat 50% 0;
padding-left: 20px;
}
所以,起初,我认为有<span>
件事会奏效。
然后,我尝试了这个,它无缝地工作:
h3:before{
content: url('your url');
}