【问题标题】:add the_post_thumbnail as CSS Background, in wordpress theme在 wordpress 主题中添加 the_post_thumbnail 作为 CSS 背景
【发布时间】:2016-06-02 07:39:59
【问题描述】:

我正在尝试将我的特色图片设置为 CSS 中的背景图片。

我需要在 HTML 和 CSS 的两个地方显示相同的特色图片。

如何在 CSS 中使用the_post_thumbnail()

HTML

 <div class="magnify">
    <div class="large"></div>
    <img class="small" <?php the_post_thumbnail( 'large', array
    ('class' =>'img-      responsive') ); ?> />
 </div>

CSS

.large {background: url('img/image.jpg') no-repeat;}

【问题讨论】:

  • 您需要为此使用内联 CSS - 例如在您的 HTML 元素上使用 style="background-image: ......." - 因为您无法将 PHP 值放入 CSS。
  • 请用 wordpress 查询完成代码

标签: php css wordpress


【解决方案1】:

正如 Tim Malone 在 cmets 中所说,您需要使用内联样式来做到这一点。你可以这样做:

<?php
$thumbnail = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'large');
list($url, $width, $height, $is_intermediate) = $thumbnail;
?>

<div class="large" style="height:<?php echo $height; ?>px;background-image:url(<?php echo $url; ?>);background-repeat:no-repeat;"></div>

请注意,我使用的是wp_get_attachment_image_src,以便在需要时获取图像尺寸。本例就是将div的高度设置为图片的高度。

【讨论】:

  • @FarooqAhmad 谢谢,我添加了background-repeat:no-repeat;
  • @FarooqAhmad 您也可以将background-repeat:no-repeat; 添加到您的 css 文件中,因为它不依赖于 php。你可以.large {background-repeat: no-repeat;}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-25
  • 2021-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多