【问题标题】:Using :before and :after pseudo-elements with images在图像中使用 :before 和 :after 伪元素
【发布时间】:2017-08-05 17:33:34
【问题描述】:

我想知道您如何在 ::after 伪元素中格式化 Content CSS?

我正在尝试创建一个 h1 标题,它的左侧和右侧都有小图像。

到目前为止我的代码:

HTML:

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

CSS:

h1 {
  text-align: center;
}

h1:before {
  content: ("images/NikonD100_40x30.jpg");
}

【问题讨论】:

    标签: html css image pseudo-element


    【解决方案1】:

    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");
    }
    &lt;h1&gt;This Week's Photo Features&lt;/h1&gt;

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

    演示:

    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");
    }
    &lt;h1&gt;This Week's Photo Features&lt;/h1&gt;

    如果您使用图像作为背景,您可以通过在 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;
    }
    &lt;h1&gt;This Week's Photo Features&lt;/h1&gt;

    【讨论】:

    • 简单而好答案!
    猜你喜欢
    • 2020-09-20
    • 2018-10-06
    • 2011-04-02
    • 2013-06-15
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    • 1970-01-01
    相关资源
    最近更新 更多