使用:before和:after伪元素与图片

6

我想知道如何在::after伪元素中设置内容CSS格式?

我试图让一个h1标题左右两侧都有小图片。

到目前为止,我的代码如下:

HTML:

<h1>This Week's Photo Features</h1>

CSS:

h1 {
  text-align: center;
}

h1:before {
  content: ("images/NikonD100_40x30.jpg");
}
1个回答

11

使用此格式,content属性可以接受URL:

content: url("the url")

演示:

h1 {
  text-align: center;
}

h1:before {
  content: url("https://picsum.photos/40/40");
}

h1:after {
  content: url("https://picsum.photos/40/40");
}
<h1>This Week's Photo Features</h1>

另一种选择是将图像设置为伪元素的背景:

Demo:

h1 {
  text-align: center;
}

h1:before, h1:after {
  display: inline-block;
  width: 40px;
  height: 40px;
  content: '';
}

h1:before {
  background: url("https://picsum.photos/40/40");
}

h1:after {
  background: url("https://picsum.photos/40/40");
}
<h1>This Week's Photo Features</h1>

如果您将图像用作背景,可以通过在 H1 元素上使用多个背景来摆脱伪元素。

演示:

h1 {
  height: 40px;
  padding: 0 40px;
  text-align: center;
  background: url("https://picsum.photos/40/40") left no-repeat,
              url("https://picsum.photos/40/40") right no-repeat;
}
<h1>This Week's Photo Features</h1>


简单而精彩的回答! - lumio

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接