【问题标题】:Calling a background image within the HTML for dynamic loading在 HTML 中调用背景图片进行动态加载
【发布时间】:2015-08-18 11:02:52
【问题描述】:

我想知道是否有可能在 HTML 文档中包含一个表现得像背景图像的图像(目前在 CSS 中完成)?原因是客户端可以通过 CMS 上传背景图片,而不是我自己必须在 CSS 中手动为客户端上传(他们无权访问)。

这是我要创建的效果:http://codepen.io/anon/pen/wabjyg

HTML

<div>
  <h1>An example of text over an image</h1>
</div>

CSS

div {
  background: url(http://lorempixel.com/g/1100/300/) no-repeat;
  width:100%;
  height:100%;
  background-size:cover;
  }

其中一种方法是将背景图像设置为像这样的内联样式...http://codepen.io/anon/pen/aOrGYX - 这样我就可以在模板中创建一个动态标签,该标签会拉取他们在 CMS 中上传的图片路径。

HTML

<div style="background-image: url('http://lorempixel.com/g/1100/300')">
  <h1>An example of text over an image</h1>
</div>

CSS

div {
  background-repeat: no-repeat;
  width:100%;
  height:100%;
  background-size:cover;
  position:relative;
}

只是想知道是否有另一种方法可以在 HTML 标记中不使用内联样式?可能会欺骗 IMG 标签使其表现得像背景图片?

【问题讨论】:

    标签: html css


    【解决方案1】:

    您可以使用object-fit 来获得img 的行为,就像背景图片一样:

    html, body {
      height:100%;
      margin:0;
      padding:0;
    }
    
    div {
      background-repeat: no-repeat;
      width:100%;
      height:100%;
      position: relative;
    }
    
    img {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    
    h1 {
      font-family:sans-serif;
      margin:0;
      color:#fff;
      position:absolute;
      letter-spacing:-1px;
      text-align:center;
      left:50%;
      top:50%;
       text-shadow:0 0 30px rgba(0,0,0,0.8);
      -webkit-transform: translateY(-50%);
      	-ms-transform: translateY(-50%);
      	transform: translateY(-50%);
      -webkit-transform: translateX(-50%);
      	-ms-transform: translateX(-50%);
      	transform: translateX(-50%);
    }
    <div>
      <img src="http://lorempixel.com/g/1100/300">
      <h1>An example of text over an image</h1>
    </div>

    【讨论】:

    • 感谢 Thomas,如果我不支持 IE,这将是理想的选择,但它必须至少支持 IE9,最好是 IE8,所以这不是一个选项,但仍然非常有用。如果没有其他解决方案,我会将其标记为答案,因为它已经回答了问题。
    • 哦,对不起,不知道。支持 IE9/8 可能会很痛苦。
    【解决方案2】:

    经过一番谷歌搜索后,我发现 this 教程提供了不同的解决方案。

    您可以在标题中添加额外的样式表,例如 background.php

    <link rel='stylesheet' type='text/css' href='css/background.php' />
    

    在该文件中,您可以设置变量并在样式表中使用它们,就像这样。

     <?php
            header("Content-type: text/css; charset: UTF-8");    
    
    // DB Query here (or pass it with a function)
    
           $background = "/img/user/background/1.png";
        ?>
    
    body, html { background: url(<?php echo $linkColor; ?>); }
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2021-04-30
      • 2015-10-04
      • 1970-01-01
      • 2017-08-17
      • 2015-08-24
      • 1970-01-01
      • 2010-09-25
      相关资源
      最近更新 更多