Home  >  Q&A  >  body text

Why can't text in HTML programs be displayed horizontally and centered?

<p>I'm currently trying to code my own Snake game and would like the title and actual game image to be in the center of the site. After I tried to insert the button to restart the game, everything broke down. Even if I try to undo all the changes, I can't seem to get the text to center. Additionally, <code>gameOverMessage</code> 1) is not hidden at all and 2) does not apply any style changes I apply in JavaScript. I'm a complete beginner so any advice would be greatly appreciated and valued! </p> <p>Here is my CSS script using all relevant elements: </p> <pre class="brush:css;toolbar:false;">#snakeboard { position: relative; top: 50%; left: 500px; transform: translate(-50%, -50%); z-index: -1; } #gameOverMessage { z-index: 1; text-align: center; position: relative; font-size: 150px; color:rgb(235, 28, 28); font-weight: bold; } .hidden { display: none; } </pre> <p>For the problem I had with the game over message, I inserted class = "hidden" and then removed this tag after the <code>has_game_ended</code> function was activated. However for some reason this was not registered. </p> <pre class="brush:html;toolbar:false;"><h1 class="h1">My Snake Game</h1> <p class="p1">Score:</p> <div id="score"></div> <canvas id="snakeboard" width="400" height="400"></canvas> <div id="gameOverMessage" class="hidden"> game over! </div> </pre> <p>Delete "hidden" class</p> <pre class="brush:js;toolbar:false;">function main() { changing_direction = false; clear_board(); drawFood(); drawSnake(); move_snake(); if (!has_game_ended()) { setTimeout(main, 200); } else { const gameOverMessage = document.getElementById("gameOverMessage"); gameOverMessage.classList.remove("hidden"); } } </pre> <p><br /></p>
P粉974462439P粉974462439431 days ago503

reply all(1)I'll reply

  • P粉250422045

    P粉2504220452023-08-16 09:07:14

    Here is your code, from what I can see it seems to be completely working. All I did here was add a button to toggle the hidden class.

    function toggleHiddenClass(){
      document.querySelector('#gameOverMessage').classList.toggle('hidden');
    }
    #gameOverMessage {
        z-index: 1;
        text-align: center; 
        position: relative;
        font-size: 150px; 
        color:rgb(235, 28, 28);
        font-weight: bold;
    }
    
    .hidden {
        display: none;
    }
    <button type="button" onclick="toggleHiddenClass()">toggle hidden class</button>
    
    <div id="gameOverMessage" class="hidden">
        Game Over!
    </div>

    reply
    0
  • Cancelreply