Creating an HTML table that adjusts to the screen height with square-shaped cells

var grid = document.getElementById("grid");
var size = 50;

for (var y = 0; y < size; y++) {
var currentRow = grid.insertRow(0);
for (var x = 0; x < size; x++) {
var currentCell = currentRow.insertCell(-1);
currentCell.style.height = currentCell.style.width = `calc(100vh / ${size})`;
currentCell.style.backgroundColor = (x+y)%2 == 0 ? "Blue" : "Red";
}
}
body {
margin: 0;
}

table#grid {
border-collapse: collapse;
height:100%; 
}
<html>
<body>
<table id="grid" align="center"></table>
</body>
</html>

Seeking a solution for creating a table that perfectly fits the height of the screen with squared cells, the current approach using hidden images only provides cell squares that are almost perfect. Avoiding the use of absolute spacing, the goal is to achieve the desired result solely using CSS and JavaScript. The table size will be dynamic at runtime, but for this example, let's consider a 2 by 2 grid:

<table>
    <tr>
        <td><img src='placeholder.png'></td>
        <td><img src='placeholder.png'></td>
    </tr>
    <tr>
        <td><img src='placeholder.png'></td>
        <td><img src='placeholder.png'></td>
    </tr>
</table>

Corresponding CSS for the layout:

table {
    height: 100%;
}

img {
    height: 100%;
    width: auto;
    visibility: hidden
}

Any simple ideas to achieve this without excessive complexity are greatly welcomed.

Answer №1

Utilizing CSS calc allows you to dynamically calculate height and width. To experiment with this feature, you can implement the following code snippet:

.blue {
  background-color: blue;
}

.red {
  background-color: red; 
}

body {
    margin: 0;
}

td {
  height: calc(100vh / 2);
  width: calc(100vh / 2);
}

table {
    border-collapse: collapse;
}
<table>
    <tr>
        <td class="blue"></td>
        <td class="red"></td>
    </tr>
    <tr>
        <td class="red"></td>
        <td class="blue"></td>
    </tr>
</table>

If you require further customization, you can integrate JavaScript to adjust the grid size dynamically and recalculate the dimensions of each cell accordingly.

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

An issue with displaying images has been identified within Next.js, resulting in an error message related to the hostname

Encountering an error when using next js Image next.config.js: module.exports = { images: { domains: ['localhost'], }, }; Error image: https://i.stack.imgur.com/RvsdH.png I am struggling to understand how to correctly set up the image ...

Updating materials within the Forge

Currently, we have implemented a system where the client retrieves object states when the page loads, changing the colors of 'pending' objects in the model. We continue to poll for changes to update the coloring - initially coloring pending objec ...

Exploring the best practices for rendering nested array elements in React.js

Is there a way to display only one URL from a nested array in React using CardMedia component? https://i.sstatic.net/K6JDz.png {props.currentTodos.map((currentTodo) => ( <CardMedia className={cl ...

Tips for extracting the two characters following a space in a string with or without the use of regex

How can I extract only the initials of 2 characters after spaces? See the code snippet below: const name = "John Peter Don"; const result = name.match(/\b(\w)/g).join(''); console.log(result)// JPD->> i want only JP ...

Repetitive NodeJS event triggers within Electron-React application causing unexpected behavior

In my custom software package (referred to as PACKAGE_A), I have implemented various automated tasks using a node script. This package includes a Notifier module that creates and exports an EventEmitter. (The entire project is structured as a Monorepo) co ...

Unable to alter the state through the URL bar using ui-router

I am facing an issue where I get redirected to the home state whenever I try to directly access a URL like mysite.com/#!/about. My menu with ui-sref links is functioning correctly, but when it comes to nested states, I encounter problems switching betwee ...

I am attempting to arrange variables based on the key of the json nested within another json

It's a bit challenging to condense my goal into one question, but I'll try my best to clarify. I currently have a JSON array that represents various HTML slider elements categorized within 3 control panes: Basic, Interface, and Advanced. Each pa ...

Load Angular modules dynamically

Is there a way to dynamically load a module (js, css and html) using a single directive at any point during the app's lifecycle? <my-module id="contacts"></my-module> The template for this directive looks like this <my-module id="con ...

Having trouble with the addEventListener function not working on a vanilla JS form?

I'm struggling to get a form working on a simple rails project. The idea is to collect a name and date from the form and display them on the same page using JS. Later, I'll process this information to determine if it's your birthday and cal ...

Organize Radio Selectors

My intention was to align the radio buttons as shown in the image below: https://i.stack.imgur.com/oPTjD.jpg However, the final result looked like this https://i.stack.imgur.com/Mixga.jpg Below is the code for your reference HTML <div class="form ...

Error Message Design in ASP.NET

I am currently developing a website using .net, which is a new technology for me. Here is the snippet of code I am working with... <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ValidationGroup="V1" Display="Dynamic" ...

Steps to include a HTML webpage within another page

I need assistance with a scenario involving two separate HTML pages on different servers. Merchant Form - Server A Payment Form - Server B Here's the desired scenario: The user completes all necessary fields on the Merchant Form and clicks submit. ...

Forcing a property binding update in Angular 2

Take a look at this particular component import {Component} from 'angular2/core' @Component({ selector: 'my-app', providers: [], template: ` <div> <h3>Input with two decimals</h3> <input type ...

I encountered an issue with adding a console log in the getStaticProps() function that resulted in the error: SyntaxError: Invalid Unicode escape sequence at eval (<anonymous>

Welcome to my users.js page! import React from 'react' const displayUsers = ({users}) => { return ( <> { users.map(user => { return <div key={user.id}> {user.name} </div> }) } </&g ...

Is it possible for me to generate values using PHP that can be easily read by JavaScript?

I'm currently building a website and I am facing some challenges when trying to incorporate JavaScript for real-time calculations. Here are my issues: Is there a more efficient way to avoid manually typing out the code for each level up to 90, lik ...

Differences Between Bootstrap Source Code and Bootstrap CDN Link

I am in the process of updating the user interface for my website, utilizing Bootstrap 5.3. Initially, I utilized the CDN link provided in the official documentation. Recently, I acquired Bootstrap Studio as a tool to streamline the UI development process. ...

What is the purpose of having a constructor in Typescript when an interface is already used for a class?

Is it necessary to have a constructor in my class if the class already implements an interface? It seems like redundant code to me. interface PersonInterface { firstname: string; lastname: string; email: string; } class Person implements Pe ...

Adding the target='_parent' attribute to the infowindow of a Google Fusion Map by utilizing a click event listener

As someone who is relatively new to Google Fusion, I am eager to expand my knowledge and skills. Recently, I created a customized map with an infowindow and embedded it onto my website using the FusionTablesLayer Wizard. I wanted to avoid using the target= ...

What is the proper way to utilize variables in package.json with npm version 7.x.x?

I am looking to utilize npm scripts to access keys found in the directories section. "directories": { "client": "client", "server": "server" }, "scripts": { "test:client&qu ...

Arranging search findings based on relevance using javascript

I'm developing a personalized search feature. Currently, when I type "The R," the search results list starts with The Fellowship of the Ring because the phrase "the ring" is in its .text property. However, I want The Return of the King to appear first ...