通过 CSS 从 PHP 变量中的值设置元素的背景图像
Setting an element's background image via CSS from a value in a PHP variable
有没有办法使用 php 变量来操纵 css?
我想将用户在 wordpress post 中选择的图像(特色图像)添加到特定 div 的背景中。我知道如何混合 php 和 html 但是,有没有一种方法可以对 css 做同样的事情?
我正在获取图像:
$img = get_the_post_thumbnail_url($post_id, 'mySize');
嗯,您已经知道如何混合使用 PHP 和 HTML,对吧?然后您只需执行相同的操作,但在 <head>
中创建一个 <style>
元素。你把你的 CSS 放在这个元素中。像这样:
<head>
<style>
div#myDivId { background-image: url("<%= $img %>"); }
</style>
</head>
你可以做的是这样的:
<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小图片。
有没有办法使用 php 变量来操纵 css?
我想将用户在 wordpress post 中选择的图像(特色图像)添加到特定 div 的背景中。我知道如何混合 php 和 html 但是,有没有一种方法可以对 css 做同样的事情?
我正在获取图像:
$img = get_the_post_thumbnail_url($post_id, 'mySize');
嗯,您已经知道如何混合使用 PHP 和 HTML,对吧?然后您只需执行相同的操作,但在 <head>
中创建一个 <style>
元素。你把你的 CSS 放在这个元素中。像这样:
<head>
<style>
div#myDivId { background-image: url("<%= $img %>"); }
</style>
</head>
你可以做的是这样的:
<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小图片。