Adjustable dimensions for a collection of squares based on screen size

I am currently designing a grid composed of 1:1 squares and allowing the user to continually add more squares. My main goal is to ensure that the size of each square maintains its aspect ratio while being able to resize accordingly. The challenge lies in keeping the squares visible on the page without any need for scrolling, making the webpage responsive in terms of both width and height.

While testing, I have managed to create an example where a new square is added every second. However, I am facing difficulties in maintaining the height aspect of the squares, even though I have successfully implemented it for the width.

setInterval(() => {
                // console.log(document.getElementsByClassName('square-container')[0]);
                document.getElementsByClassName('square-container')[0].innerHTML += ("<div class='square'></div>");
            }, 1000);
.square-container {
                display: flex;
                flex-wrap: wrap;
            }

            .square {
                position: relative;
                flex-basis: calc(33.333% - 10px);
                margin: 5px;
                box-sizing: border-box;
                background: red;
                transition: background 1s;
            }

            .square::before {
                content: "";
                display: block;
                padding-top: 100%;
            }
<div class="square-container">
                <div class="square"></div>
            </div>

I am utilizing only basic HTML, CSS, and JavaScript without relying on UI libraries like Bootstrap.

Answer №1

To optimize layout, consider using Float instead of wrap and setting the square-container to display block.

<div>
<div id="square-container">
    <div id="square"></div>
    <div id="square"></div>
    <div id="square"></div>
    <div id="square"></div>
    <div id="square"></div>
    <div id="square"></div>
    <div id="square"></div>
    <div id="square"></div>
</div>
</div>

#square-container{
  display: block
}
#square{
    float: left;
    height: 100px;
    width: 100px;
    background-color: orangered;
    margin: 1px;
}

Answer №2

How about considering a pure javascript solution?

Simply establish an initial value and let JavaScript handle all the calculations whenever a square is added.

// Function for resizing the squares
function resizeSquares(){
    // Access the squares
    squares = document.getElementsByClassName('square');
    for (i=0;i<squares.length;i++) {
        // Set the width of each square based on the window's width
        squares[i].style.width = document.body.clientWidth / squarePerRow + 'px';
        // Maintain the aspect ratio by setting the height equal to the width
        squares[i].style.height = squares[i].style.width;
    }
}

// Establish the initial capacity of squares per row
squarePerRow = 3;

// Initialize the size of the squares
resizeSquares();

setInterval(function(){
    // Add a new square
    document.getElementById('container').innerHTML += '<div class="square"></div>';
    // Check if the squares exceed the window height
    if(document.body.clientHeight > document.documentElement.clientHeight) {
        // If they do, increase the capacity of squares per row by one
        squarePerRow = squarePerRow + 1;
    }
    // Resize the squares
    resizeSquares()
}, 1000)
#container {
    display: flex;
    flex-wrap: wrap;
}

.square {
    background: red;
    border: 5px solid white;
    box-sizing: border-box;
    transition: all, 0.5s;
}
<div id="container">
    <div class="square"></div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attempting to create a discord bot using Selenium in Python for seamless integration

I am currently attempting to create a Discord bot using Selenium in Python. I have been working on the script to connect the bot to my discord account. Below are the required imports: from selenium import webdriver from selenium.webdriver.common.keys imp ...

Loading Animation with jQuery and Minimum Time Delay

Hello there, I am looking for a way to establish a minimum time duration for an onload function to ensure that a div is displayed for at least 2 seconds. Similar to setting a min-width or min-height, I want the div to be shown for a minimum of 2 seconds e ...

What is the reason for not using constants for events in the Node.js programming language?

Although I am new to node.js, my programming background is extensive. I have noticed that in tutorials and production code, developers tend to use hard-coded strings rather than constants to identify events. To illustrate this point, I randomly selected a ...

how can JavaScript be used to retrieve an object based on a condition from an array of objects and an ArrayList

My JavaScript challenge involves working with an array of objects called arrobj and a list called prgList. The goal is to extract the names from arrobj based on the programs listed in prgList. If the program exists in arrobj, it should be displayed accor ...

Tips for referencing the second class when two classes share the same name in Selenium WebDriver

I am trying to retrieve the text from the second "109-top-dark-grey-block ng-binding" class, which is currently null but will contain some text in the future. I have attempted using tabIndex and nth-child selectors, but neither have been successful. " < ...

The eel feature results in no output

During my Python program development using the Eel module, I encountered an issue. The problem is that the eel.getImgSrc(path) function returns null when trying to retrieve image's byte data. Take a look at this example: -----web/main.js------ async ...

Display only alphabetic characters in the text field

I have a jQuery function that I am working on: $('#contact_name').on('input', function() { var input=$(this); var re =/^[A-Za-z]+$/; var is_email=re.test(input.val()); if(is_email) { } else { } }); This function is targeted at the fol ...

What is the best way to identify when the soft-keyboard is hidden in the Android browser

Having trouble with the Android Webkit browser and need to manually detect when the soft-keyboard is hidden by pressing the button in the top right corner. https://i.stack.imgur.com/x11Vp.jpg In the image above, pressing the button hides the soft keyboar ...

Tips for transferring POST body data to a different route without losing any information

Assuming I have the following route: app.post('/category',function(req,res){ res.redirect('/category/item'); }) In this scenario, the user will submit data to the '/category' route and then automatically be redirected ...

The error message "TypeError: Trying to access properties of an undefined object (reading '800')" is being displayed

Every time I launch my application, I encounter the error message: "TypeError: Cannot read properties of undefined (reading '800')". import React, { useState } from 'react'; import { Menu, MenuItem, Avatar, Box, ThemeProvider} ...

AJAX cannot be used with the current session

I am facing an issue with a directory containing files that are used only as modal. These PHP files have the following format: "modal.filename.php". Here is an example: "modal.user.php": <?php session_start(); $_SESSION['test'] = 1; echo & ...

Ensuring form labels are properly aligned with input-group-prepend in Bootstrap

Currently, I am developing a python/django website using bootstrap, and I have encountered an issue that I cannot resolve independently. It has been quite some time since I last worked with python/django/bootstrap, so I may be overlooking something? <fo ...

Guide on creating a JSONP request

My goal is to perform cross-site scripting. The code snippet below shows the jsonp method, which appears to fail initially but succeeds when switched to a get request. I am trying to achieve a successful response using the jsonp method. I have confirmed th ...

Arrange data into columns on a website

In my project, I'm exploring the challenge of creating a square 2 x 2 grid alongside a rectangular column on the right-hand side. While attempting to implement a grid system for the 2 x 2 layout, I encountered issues with the alignment of the rectang ...

How far apart are two surfaces when they are rotated along the Y-axis

Access Code: Click here to access the code I am trying to make sure that the red surface lies completely flat on top of the gray surface. However, there seems to be a gap (marked ??) between the two surfaces when I rotate 'modifier1'. How can I ...

index.js file in npm package optimized for browser compatibility using Babel transpiler

Struggling to create and set up an npm package for use in browser environments, particularly with generating the index file. Currently have the testpackage linked to my test application using npm link in both project directories. The test application is c ...

What is the correct regex expression for validating decimal numbers between 1.0 and 4.5?

I'm having trouble creating an expression to validate numbers between 1.0 to 4.5 accurately. The current expression I'm using is not working as intended: /^[1-4]{0,1}(?:[.]\d{1,2})?$/ The requirement is to only allow values between 1.0 to ...

the reason behind the peculiar behavior of angularjs ng-include

I am attempting to utilize an ng-template to iterate through my args in order to create an indented menu content. Unfortunately, I have encountered issues with ng-include not working as expected. I have tried adding a quote but it still does not work. For ...

Sending multiple objects using Ajax and fetching them in PHP

I'm facing an issue with posting a form and an array to my PHP script. My current approach involves using the following code: var json_data = JSON.stringify(data_vendor); //array to be posted $.ajax({ url: &ap ...

Executing a JavaScript function when an HTML page is loaded within an OBJECT Tag

I have a situation where I am loading an HTML page inside an object tag. Since the iPad does not support iFrames, I decided to use the object tag to load external HTML pages into a container. Everything is working well so far, but now I want to be able t ...