php - 如何在 css 中使用 php 制作内容属性

标签 php html css arrays

所以我从一个数组中获取一些信息,用于我制作的条形图表。 这是 CSS:

<style>
.outer,
.inner,
.target {
  height: 14px;
  margin-bottom: 5px;
}
.outer {
  background-color: #cccccc;
  width: 80%;
  margin: 20px auto;
  position: relative;
  font-size: 10px;
  line-height: 14px;
  font-family: sans-serif;
}
.inner {
  background-color: green;
  position: absolute;
  z-index: 1;
  text-align: right;
  border-right: 2px solid black;
}
.inner:after {
  content: '$avg_width';
  display: inline-block;
  left: 10px;
  position: relative;
  height: 100%;
  top: -14px;
}
.target {
  background-color: transparent;
  width: 19px;
  position: absolute;
  z-index: 2;
  color: black;
  text-align: right;
  border-right: 2px dotted black;
}
.target:after {
  content: 'Target: $target_width';
  display: inline-block;
  left: 28px;
  position: relative;
  height: 100%;
  top: 14px;
}
.solid_line {
  color: black;
  float: right;
  width: 3px;
  border-right: 3px solid black;
  height: 16px;

}
</style>

这是 php:

<?php

    $target = number_format((float)$data->data[2][32][3], 2, '.', '');
    $array = [];
    $sum = 0;
    $path = $data->data[2];
    $bar_width = '200px'; 
    foreach($path as $key => $item){
        if($key > 1 && isset($item[5])){ 
            $array[] = (int)$item[5];
            $sum += (int)$item[5];
        }
    }
    $avg = ($sum / count($array));
    $base   = max($target, $avg);
    $target_width = $bar_width / 100 * ($target / $base * 100);
    $avg_width = $bar_width / 100 * ($avg / $base * 100);
    $percent = $avg / $target;                       
?>

这是 HTML:

<div class="outer"> 
    <div class="target">
    </div>                   
    <div class="inner">
    </div>
</div>

如您所见,我尝试在 css 中使用 content 属性并在其中使用 php,但由于某种原因它不显示结果。

最佳答案

那是因为您直接在 CSS 中访问 PHP 变量。 HTML/CSS 在客户端执行,而 PHP 在客户端执行。

因此您需要在页面 CSS 中回显 PHP 变量。像这样:

.inner:after {
  content: '<?php echo $avg_width ?>';

上面的 echo 代码将在服务器端执行,并为客户端 CSS 赋值以正确呈现元素。

Make sure You're using it on ON PAGE/INLINE CSS, this won't work on external .CSS files.

关于php - 如何在 css 中使用 php 制作内容属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38014746/

相关文章:

html - 如何让右侧 float 菜单溢出时滚动?

内列中的 CSS 100% 高度

HTML 图像缩放

html - Bootstrap CSS - 无法同时获取背景颜色和图像

javascript - PHP/JavaScript : how to pass array from PHP to JavaScript

javascript - 在ajax请求中调用ajax请求

php - 如何在标记 <code> </code> 中将正则表达式字符 < 和 > 替换为 < 和 >?

php - 如何更好地解耦我的数据层并限制我的单元测试范围?

css - 在 Firefox 中使用缩放变换的 CSS 过渡效果后图像移动/跳跃

javascript - 背景大小不受输入字段影响