Search code examples
htmlcssgridtetris

Responsive Tetris grid using div tags


I am trying to build a Tetris game using javaScript and HTML without any tutorial. My methods are very primitive. I am making my grid using div tags. The problem is that it is not as responsive as I expected.

This is one row from my grid:

                <div class="row">
                <div id="sq1" class="square fender">&nbsp;</div>
                <div id="sq2" class="square free">&nbsp;</div>
                <div id="sq3" class="square free">&nbsp;</div>
                <div id="sq4" class="square free">&nbsp;</div>
                <div id="sq5" class="square free">&nbsp;</div>
                <div id="sq6" class="square free">&nbsp;</div>
                <div id="sq7" class="square free">&nbsp;</div>
                <div id="sq8" class="square free">&nbsp;</div>
                <div id="sq9" class="square free">&nbsp;</div>
                <div id="sq10" class="square free">&nbsp;</div>
                <div id="sq11" class="square free">&nbsp;</div>
                <div id="sq12" class="square fender">&nbsp;</div>
            </div>

I am using this style for each square:

.square {
float: left;
width: 6%;
padding-bottom: 6%; 
border-top: 1px solid black;
border-left: 1px solid black;}

But my squares are changing into rectangles when I resize page. I also use similar smaller grid for showing the next piece. It is surrounded by other tags, which probably deforms it. (The whole project is on codepen.)

Is there some easy way to make my squares square? I found several ways how to make responsive square, but none of them worked for me.


Solution

  • You're nearly there with what you have already.

    Looking at your markup, it appears that you want 12 squares in a row so to do that I used width: 8%;. And, as you rightly tried you need to add a padding-bottom with a matching 8% also. E.g.

    .square {
        float: left;
        width: 8%;
        padding-bottom: 8%; /* = width for a 1:1 aspect ratio */
        border-top: 1px solid black;
        border-left: 1px solid black;
    }
    

    The reason your squares weren't fixed in their aspect ratio is because of the &nbsp; you added to all of your div squares. You can't add content directly inside the squares (without absolutely positioned children) as it would increase their height, thus the squares wouldn't be squares anymore.

    Once you remove all of these non-breaking spaces, your squares will maintain their aspect ratio.

    Finally, I tidied up a couple of minor albeit unrelated HTML errors, and the full forked example is here: https://codepen.io/ahdigital/pen/LeNNWY?editors=1100