3

我有 wordpress 侧边栏:

<h3 class="widget-title">TITLE OF SIDEBAR</h3>

我需要在“侧边栏的标题”之前显示小图标。我可以使用 CSS 吗?

或者我必须手动将图像添加到代码中?喜欢:

<h3 class="widget-title"><img src="">TITLE OF SIDEBAR</h3>
4

9 回答 9

16

伪元素会做你想做的事。使用:before伪元素,您的 CSS 将如下所示:

h3.widget-title:before {
    content: url('/path/to/image');
}

这将在 的文本内容之前放置一个图像<h3>,但是这根本不会改变 DOM,这一点很重要。

可以在 CSS Tricks 上找到关于伪元素如何工作的一个很好的解释。

于 2013-06-08T21:15:04.387 回答
5

如果你的图片是 10px 宽,你可以试试这个:

.widget-title {
background: url(smallicon.png) left top no-repeat;
padding-left: 10px;
}
于 2013-06-08T21:18:03.573 回答
4

保留您的 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;
}
于 2013-06-08T21:48:42.017 回答
1
.widget-title:before {
  content: url(path/to/image.png);
}

您可以在https://developer.mozilla.org/en-US/docs/Web/CSS/content找到更多信息。

于 2013-06-08T21:14:15.967 回答
1
h3:before {
content: url('https://www.google.com/images/srpr/logo4w.png')
}

示例http://jsfiddle.net/KCXVM/

于 2013-06-08T21:16:44.520 回答
0

是的,你可以在 CSS 中做到这一点。

只需使用:before伪选择器,如下所示:

widget-title:before {
    content:url('imagename.png');
}

或者,当然,使用h3:before { ... }它来应用于所有h3元素。

这是一个适合您的工作示例

浏览器兼容性:这适用于所有常见浏览器,IE7 或更早版本除外。

于 2013-06-08T21:18:09.510 回答
0

为什么不简单地将图像应用为背景?

.widget-title {
    background: url(...) no-repeat 50% 0;
    padding-left: 20px;
}
于 2013-06-08T21:18:13.410 回答
0

所以,起初,我认为有<span>件事会奏效。

然后,我尝试了这个,它无缝地工作:

h3:before{
content: url('your url');
}
于 2013-06-08T21:21:01.137 回答
0
于 2018-06-01T04:09:24.183 回答