【问题标题】:Setting an element's background image via CSS from a value in a PHP variable通过 CSS 从 PHP 变量中的值设置元素的背景图像
【发布时间】:2019-02-02 09:26:29
【问题描述】:
有没有办法使用php变量来操作css?
我想将用户在 wordpress 帖子中选择的图片(特色图片)添加到特定 div 的背景。我知道如何混合 php 和 html,但是有没有办法用 css 做同样的事情?
我正在获取图像:
$img = get_the_post_thumbnail_url($post_id, 'mySize');
【问题讨论】:
标签:
php
css
wordpress
background-image
【解决方案1】:
嗯,您已经知道如何混合 PHP 和 HTML,对吧?然后你只需做同样的事情,但在<head> 中创建一个<style> 元素。你把你的 CSS 放在这个元素中。像这样的:
<head>
<style>
div#myDivId { background-image: url("<%= $img %>"); }
</style>
</head>
【解决方案2】:
你可以这样做:
<head>
<style>
.user img { background-position: center center; background-repeat: no-repeat; background-size: cover; }
</style>
</head>
...
<div class="user">
<img src="images/trans.png" width="50" height="50" style="background-image:url(<?php echo $img; ?>);" />
</div>
其中 trans.png 是一个小的透明 png 图片。