0

I'm learning JS, HTML and CSS and making a very basic Snake game using JS, HTML and CSS. I'm getting a strange CSS top offset when I have multiple objects.

For example: The HTML I'm using looks like:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="grid" id="grid">
        <div class="snake" id="snake"></div>
        <div class="dot" id="dot"></div>
    </div>
<!--    <script src="app.js"></script>-->
</body>
</html>

With CSS styles:

.grid {
    width: 1000px;
    height: 1000px;
    border: 1px solid brown;
    margin: auto;
}

.snake {
    width: 20px;
    height: 20px;
    background-color: green;
    background-size: 20px 20px;
    position: relative;
    top: 200px;
    left: 200px;
}

.dot {
    width: 20px;
    height: 20px;
    background-color: blue;
    background-size: 20px 20px;
    position: relative;
    top: 200px;
    left: 200px;
}

This leads to this output: Output display using Chrome

As can be seen, even though they have the same top and left values in the CSS, the is a top offset. Why is this and how do I allow them to overlap?

Thank you for your time.

  • I think you’re asking why your snake and dot are not in the same top 200px and left 200px position (one overlapping the other). Position relative changes the position, but each component still takes up space. If you want the squares to be able to cover another, you can use `position: absolute;` – Rich DeBourke Mar 26 '21 at 23:51
  • Use position: relative on the grid and position: absolute on its elements – MisteriosM Mar 26 '21 at 23:52

0 Answers0