【问题标题】:Pseudo element background-image does not work伪元素背景图像不起作用
【发布时间】:2018-02-26 05:54:08
【问题描述】:

根据other SO solutions,我已经尝试为伪元素(height: X px; width: X px;)提供明确的固定尺寸,但即使这可行,我想要一个适合其父元素的可缩放、响应式图像,因此固定尺寸不是我可以接受。如何让 background-image 显示并同时自动缩放?

HTML:

<h3>This is a title</h3>

CSS:

 h3:before{
   background-image:url('https://store.ashenglowgaming.com/wp-content/uploads/2018/02/cropped-agg-store-logo-4-FULLSIZE-1.jpg'); 
   background-size: contain;
   background-repeat: no-repeat;
   display: block;
 }

【问题讨论】:

  • h3:before中使用content:""....顺便说一句,为什么不在h3本身中使用background-image
  • 我特别希望徽标出现在标题上方,而不是在标题内部。
  • background-position: 0% 0%; 对我没有任何作用。看不到任何图像。

标签: html css


【解决方案1】:

试试这个

h3:before{
    background-image: url(https://store.ashenglowgaming.com/wp-content/uploads/2018/02/cropped-agg-store-logo-4-FULLSIZE-1.jpg);
    background-size: contain;
    background-repeat: no-repeat;
    content: '';
    height: 110px;
    display: block;
}

【讨论】:

  • 你知道我可以如何强制最小宽度吗? min-width: 150px 不起作用?
  • @user136649 可以通过 background-size 调整宽度:auto 60%;
  • @user136649 你可以给背景尺寸:100%;然后调整宽度和高度。
【解决方案2】:

尝试将这些样式添加到您的伪元素中

content: "";
top: 0;
left: 0;
bottom: 0;
right: 0;
position: absolute;

【讨论】:

  • 我害怕使用absolute。它通常会扰乱我的文档流程,因为其他元素将不再尊重它的存在,从而导致元素重叠......
  • 因为我们应用绝对相对于其父 h3,它不会影响任何其他元素。它只能影响 h3 内的元素。
【解决方案3】:

我添加了content: '';,并为伪元素指定了heightmin-width

h3:before {
  content: '';
  background-image: url('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTMdl8cg3CDenBgBdDey8W2KUfDIfKO7ZcPk6c5KtuLn8OJBzu8');
  background-size: contain;
  background-repeat: no-repeat;
  display: block;
  min-width: 150px;
  height: 40px;
}
<h3>
  This is a title
</h3>

【讨论】:

    【解决方案4】:

    您可以在h3本身中使用background,并使用background-size调整大小。

    堆栈片段

    h3 {
      background-image: url(https://store.ashenglowgaming.com/wp-content/uploads/2018/02/cropped-agg-store-logo-4-FULLSIZE-1.jpg);
      background-size: auto 40px;
      background-repeat: no-repeat;
      display: block;
      padding-top: 40px;
    }
    <div class="wrapper">
      <h3>This is a title This is a title This is a title This is a title This is a title This is a title This is a title This is a title This is a title</h3>
    </div>

    【讨论】:

    • 我的 h3 标题现在被强制退出文档流,并且它周围的元素忽略它,导致内容重叠 - 这是预期的吗?
    • @user136649 不,它不是预期的......看起来你正在使用position:absolute......如果你能分享一个工作示例来查看实际问题,那就太好了......
    • 其实我明白是什么问题。首先,height 现在必须考虑标题本身的高度 - 但问题是文本的高度会发生变化,因为它会自动换行。因此,您永远无法完全确保标题不会与图像重叠并使用此方法完全容纳在容器内?文字大小是可变的,但我们使用固定的padding-top 来清除标题。
    • @user136649 你希望你的背景图片是全宽还是固定大小...?我应用了40px padding-top 和 40px 高度的背景图像来防止重叠...
    • 你说得对,我的朋友——这是我网站的问题——你可以看截图here。在这种情况下,我更容易使用@athi 和@Anuresh 的:before 方法,因为它避免了这个问题,而无需我更多地编辑我的网站。但我会给你一个赞成票。我非常感谢您付出的努力。
    猜你喜欢
    • 2017-04-20
    • 2017-10-24
    • 2021-01-01
    • 2021-03-07
    • 1970-01-01
    相关资源
    最近更新 更多