1

I am making a website that has two background images, one of them is always the same i.e.:

background-image: url("../images/centre-image.jpg");

and the other is generated via php to show a background image at random:

    <?php
      $bg = array('large-top1.jpg', 'large-top2.jpg', 'large-top3.jpg', 'large-top4.jpg', 'large-top5.jpg', ); // array of filenames

      $i = rand(0, count($bg)-1); // generate random number size of the array
      $selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
    ?>

<img src="images/background-images/<?php echo $selectedBg; ?>" class="bg">

Making the first background the full size of the DIV no matter what size of the screen was easy enough:

div.centre-options {
    background-size: 100% auto;
}

however if I try to add similar CSS to the random generated image it doesn't work (just shows it at its full jpg size and then repeats) and not sure show to solve the problem.

4

1 回答 1

2

据我所知,生成的图像没有设置为背景,而是设置为要显示的图像,因此您不能对其应用背景样式。

您可以做两件事,或者将样式直接应用于图像标签,即

img.bg{
width:100%;
height:100%;
}

或者创建一个元素并将生成的图像添加到它的样式中,看起来像这样:

 <?php
      $bg = array('large-top1.jpg', 'large-top2.jpg', 'large-top3.jpg', 'large-top4.jpg', 'large-top5.jpg', ); // array of filenames

      $i = rand(0, count($bg)-1); // generate random number size of the array
      $selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
    ?>
<style>
div.bg{
background-image: url("images/background-images/<?php echo $selectedBg; ?>");
background-size: 100% auto;
}
</style>
<div class="bg"></div>

最好将样式放在头部标签之间

于 2013-04-22T16:30:41.843 回答