Search code examples
javascripthtmlcssweb-development-serverweb-testing

How to randomize a gradient background and align text to the center of the screen regardless of platform?


Alright, this question will be a long one, so thank you in advance to anyone who sticks through it. Simply put, I'm trying to make a very simple website for a relative for christmas, but I've run into 2 issues which the internet as of yet hasn't given me a solution to. I'll link the entire current code at the bottom, most of written by a friend far more proficient than me. I'll try to explain my issues as briefly as possible, as follows:

  1. How to randomize the gradient background of the site

    • Although I have nothing against the current background, established in the first bolded line, I think it would fit better with the changing aspect of the site to have it be randomized every time it's reloaded. However, although I've found sites such as https://codepen.io/Luc-Designs/pen/LXxBPg, https://dev.to/shantanu_jana/random-gradient-generator-using-javascript-css-529c, and even a question on the site, https://stackoverflow.com/questions/50878276/random-gradient-background-color, I haven't been able to implement any of them successfully. The page always defaults to the current gradient, but I'm not sure if I should remove the code setting it to that or what. If anyone knows how to implement a code that would randomize it, I would be extremely grateful.
  2. How to align text to the center of the screen regardless of platform

    • Although, once again, I've found sources that appear have what I want for this, I haven't been able to figure out how to implement any of them. I'm familiar with how to align the text in the center TOP PART of the screen, but I want the actual center, meaning moving it down as well, which I'm struggling with. Visible in the second bolded line, I'm aware how to reposition it, but I was in the middle of putting it in a good place when I realized that it likely wouldn't work across platforms. A quick search on my phone confirmed this, and now I'm not sure how I can orient the changing every time the site is refreshed text in the center of the screen regardless of platform or size. If this is possible, it would be awesome to know how I would implement it into the existing code.

Those 2 issues are about it, and although I'll keep searching for solutions, as I don't think either issue is very complex, I'm putting a question out here in the hope a web development expert might save me from having a subpar christmas gift. Thank you to anyone who read this.

I tried to move the text using the manual reposition code shown above, aka <h1 id="a" style=**"position:absolute; left:300px; top:300px;** font-family:Times New Roman;"> </h1>, but that won't work for my needs, as explained above, and I'm not actually sure of the center coordinates and how they would change depending on text length. The text will change, so the center of it will have to be fixed to the center of the page.

The gradient code has no issue, I just would prefer it randomized, as stated above.

Entire Code:

HTML: `

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gift</title>
    <style>
        body {
            **background-image: linear-gradient(to right, #0093E9, #80D0C7);**
        }
    </style>
</head>
<body>
**    <h1 id="a" style="position:absolute; left:300px; top:300px; font-family:Times New Roman;"> </h1>**
    <script>
        const list = [ "Text1", "Text2", "Text3", "Text4", "Text5", "Text6", "Text7", "Text8", "Text9", "Text10" ];
        document.getElementById("a").innerText = list[Math.floor(Math.random() * list.length)];
    </script>
</body>
</html>

<button onclick="location.reload();">What else?</button>

`

CSS: `

html, body {
  height: 100%;
  width: 100%;
}

`


Solution

  • First off an important piece your missing is to link your CSS to the HTML. I dont see it done in the HTML provided, this can be done in the <head> of the file by adding the following <link rel="stylesheet" href="index.css">

    Now that we have that out of the way we can get into assigning a random gradient

    First off We have restructured the HTML page to look like the following. It has some text, a button, and a container with the ID main the ID main is used in the CSS to provide the centering you were looking for

      <div id="main">
        <div id="text">
          Hello World
        </div>
        <div>
          <button onclick=handleButtonClick()>What else?</button> 
        </div>
      </div>
    

    We then edit the CSS file you have to make the main div a flexbox. This site is a great aid in understanding how flexbox changes the behaviors of the div but in short it puts all our content in the center of the div and we make the div take up 100% of the current view (see Relative Units)

    
    body{
        height: 100vh;
        width: 100vw;
    }
    
    #main{
        height: 100%;
        display:flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
    }
    

    In the script tag we will make 2 new functions. The first function randomly generates 3 values for the Red, Blue, and Green components of RGB() so that we can get a random color for the gradient The second function activates on button click. When the button is clicked we change the text as you have indicated previously but we also assign new random colors to our body's background image via gradient. To achieve this easier I am using Template Literals

    <script>
        function ranRGB(){
          var red = Math.floor(Math.random()*256)
          var blue = Math.floor(Math.random()*256)
          var green = Math.floor(Math.random()*256)
          return(`rgb(${red},${blue},${green})`) 
        }
        function handleButtonClick(){
          document.body.style.backgroundImage = `linear-gradient(to right, ${ranRGB()}, ${ranRGB()})`;
          const list = [ "Text1", "Text2", "Text3", "Text4", "Text5", "Text6", "Text7", "Text8", "Text9", "Text10" ];
          document.getElementById("text").innerText = list[Math.floor(Math.random() * list.length)];
        }
        
        var colorOne = "#0093E9"
        var colorTwo = "#80D0C7"
        document.body.style.backgroundImage = `linear-gradient(to right, ${colorOne}, ${colorTwo})`;
      </script>   
    

    When it is all put together The initial gradient is loaded, then on button click the text changes to a random part of the list and he gradient changes to a random value