【问题标题】:Add background image using php使用php添加背景图片
【发布时间】:2016-02-21 19:08:13
【问题描述】:

我正在使用 wordpress 和 ACF 插件来添加图像:

http://www.advancedcustomfields.com/resources/image/

我想在 div 中添加一张图片作为背景。 我在我的 style.css 中使用了这段代码,但它不起作用:

background-image: url(<?php $image = get_field('image_projet');?> <img 

src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />);

感谢您的帮助

【问题讨论】:

  • 您正在将 html 添加到 css 文件中。
  • 您不能在 CSS 文件中使用 PHP 代码,您可以在内联 CSS 代码(样式标签)中使用,这仍然不是最佳实践,..您能否详细说明您的问题还有,sn-p的代码不是很清楚
  • 您想通过给出的代码片段告诉我们什么?这应该是一个CSS文件吗? HTML? php?为什么要将 CSS 与 html 混合使用?您没有在 CSS 部分中回显任何内容。

标签: php wordpress image background advanced-custom-fields


【解决方案1】:

一个 css 文件包含 CSS。只是 CSS。您不能将 html 或 PHP 写入 CSS 文件。 如果要使用 PHP 生成 CSS 属性,则必须直接在 PHP 文件(视图)中使用 &lt;style&gt;...&lt;/style&gt; 标签。例如:

<?php $image = get_field('image_projet'); // fetch the ACF field ?>

<html>
    <head>
        <title>Page's Title</title>
        <style>
            .your-div {
                background-image: url('<?php echo $image; ?>');
            }
        </style>
    </head>
    <body>
        <!-- this div uses the $image URL as a background. -->
        <div class="your-div">
            Lorem Ipsum.
        </div>
    </body>
</html>

【讨论】:

  • 好的,背景中的图像有效,但我所有文章的图像都相同!每篇文章都有一个独特的图像。我试过这个代码: background-image: url('');但它不起作用。我需要“$image['alt'];”
【解决方案2】:

这样做,你不能通过 css 添加 alt 所以用标题代替,看here, SO css background image alt attribute

`<div style="background-image: url( <?php echo $image['url']; ?>); height: 200px; width: 400px; border: 1px solid black;" title= "<?php echo $image['alt']; ?>">my DIV  with a background image:</div>

【讨论】:

    猜你喜欢
    • 2017-10-16
    • 2014-11-07
    • 1970-01-01
    • 2012-01-01
    • 2010-12-29
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多