Home > Net >  How can I use PHP/HTML to display a random image as a background image
How can I use PHP/HTML to display a random image as a background image

Time:01-20

I'm trying to learn how to build a website. I've built the index page and here is the PHP and HTML.

<?php
session_start();
$png = array('png1.jpg', 'png2.jpeg', 'png3.jpg', 'png4.jpg');

$random = rand(0,4);
$picture = "$png[$random]";
?>


<!DOCTYPE HTML>
<html>  
<head>
<link rel="stylesheet" href="index.css">
</head>
<body>

<form action="login.php" method="post">
Name: <input type="text" name="name"><br>
Password: <input type="text" name="password"><br>
<input type="submit">
</form>

</body>
</html>

and here is the CSS where I link to the image file:

body{
  background-image: url('png1.png');
}

I'm running the site on replit.com and here is the png1.jpg:

enter image description here

The background image is not appearing. Only the form is showing. the link of website on replit is example

CodePudding user response:

I am not sure if your image is not showing or if it is showing in the wrong place.

using the css below you will allow you to set your background image properly.

 body {
      background-image: url('png1.png');
      background-repeat: no-repeat;
      background-attachment: fixed;  
      background-size: cover;
    }
  • Related