Angular Square Grid Design

Attempting to create a square grid layout using CSS for ng-repeat items.

Essentially, I am looking to have one big square followed by four smaller squares that combined have the same width and height as the big square.

Here is my CSS:

.container{
  width: 1398px;
}
.item{
            float: left;
            margin: 3px;
            overflow: hidden;

            width: 460px;
            height: 460px;
            background-color:black;
        }
        .item:nth-of-type(2n),
        .item:nth-of-type(3n),
        .item:nth-of-type(4n),
        .item:nth-of-type(5n) {
            width: 227px;
            height: 227px; 
        }
        .item:nth-of-type(4n){
            margin-left: -230px;
            margin-top: 236px;
        }
        .item:nth-of-type(5n){
            margin-left: -463px;
            margin-top: 236px;
        }

Everything works well until after the 5th element, then the grid breaks.

Fiddle: https://jsfiddle.net/enq1okge/4/

Answer №1

If you want to achieve a unique layout without relying on third-party libraries, consider using some nth-child trickery. While not foolproof, it can serve as a workaround in certain situations.

The basic idea is to reset the float on every 1st, 6th, 11th, 16th, and so forth elements, making them roughly twice the size of the others. This will require careful calculation based on the container's width.

In this scenario, you would use :nth-child(5n+1). After determining the selector, adjust the sizes accordingly. The larger elements should take up approximately half the container's width (container-width / 2), while the smaller ones should be one quarter of the container's width (container-width / 4).

Below is a simplified example snippet:

* { box-sizing: border-box; margin: 0; padding: 0; }
div.cont { 
width: 80vw; clear: both; margin: 8px auto;
}
div.item { 
float: left;
background-color: #33e; margin: 1px;
width: calc((80vw / 4) - 4px); height: calc((80vw / 4) - 4px);
}
div.item:nth-child(5n+1) {
width: calc((80vw / 2) - 6px); height: calc((80vw / 2) - 6px);
background-color: #e33; clear: left;
}
<div class="cont clearfix">
<div class="item"></div>
<div class="item"></div>
...
<div class="item"></div>
<div class="item"></div>
</div>

Feel free to experiment with this concept on a live fiddle: : https://jsfiddle.net/abhitalks/95rx53o6/

Note: By keeping the container's size in percentage or viewport-relative units and adjusting the children's size accordingly, you can ensure responsiveness in your design.

Answer №2

The correct application of css is as follows:

.cont{
  width: 1398px;
}
.item{
  float: left;
  margin: 3px;
  overflow: hidden;
  background:#000;
  width: 227px;
  height: 227px; 
  background-color:black;
}
.item:nth-of-type(5n + 1) {
  background-color:red;
  width: 460px;
  height: 460px;
}
.item:nth-of-type(5n - 1){
  margin-left: -230px;
  margin-top: 236px;
}
.item:nth-of-type(5n){
  margin-left: -463px;
  margin-top: 236px;
}

View the live demonstration on jsfiddle

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

Oops! The angular app encountered an error: TypeError - it cannot read property '0' of undefined. Time to debug

Having difficulty grasping the source of an error, as the html side is able to read list[3].main.temp without any issues. However, in the second loop of the generateList function, I encounter an error specifically on $scope.list[i].main.temp, which throws: ...

JavaScript Scrolling Functionality Not Functioning as Expected

I have implemented a scroll function on my website $('#lisr').scroll( function() { if($(this).scrollTop() + $(this).innerHeight()>= $(this)[0].scrollHeight) { //Perform some action here } } However, I am encountering an ...

Encountering the error message "The getStaticPaths function in Next.js requires the 'id' parameter to be provided as a string"

Having an issue with the getStaticPaths function. Every time I attempt to create a dynamic display using a parameter, it gives me an error message: A required parameter (id) was not provided as a string in getStaticPaths for / movies / [id]. However, if ...

Tips for incorporating HTML code within a select option value?

I am working with AngularJS to create a Visual Composer for a website. One feature I want to incorporate is the ability to add HTML code based on the selection made in a dropdown menu. However, I am struggling to figure out how to include the HTML within t ...

Can you explain the significance of the regular expression in a dojo configuration file named dj

As I was working on developing dojo application modules, I came across a regular expression in tutorials. var pathRegex = new RegExp(/\/[^\/]+$/); var locationPath = location.pathname.replace(pathRegex, ''); var dojoConfig = { asyn ...

Obtain a specific portion of text from a string that resembles a URL

$("#index-link")[0].search = "?isNameChecked=False&isDateChecked=False&isStatusChecked=True" Is there a way to use jQuery to identify whether isStatusChecked is set to true or false in the given string? ...

The method this.$el.querySelector does not exist

The data retrieved from the database is inserted into the input fields and submitted as a form. This data is an object that passes the value to the database. However, when I trigger this form, an error occurs. See example of the error <input id=" ...

Basic exam but located in a place that is not valid

Here is a test I am working on: // import {by, element, browser} from "protractor"; describe('intro', () => { beforeEach(() => { browser.get(''); }); it('should have multiple pages', () => { let buttonOn ...

Calculate the time difference between the stroke of midnight on a specific date and the present moment using JavaScript, node.js, and

Looking for a way to determine if the current moment is less than 3 minutes after midnight of the next date using a JavaScript Date object (e.g. 09.08.2020 15.45). This condition should evaluate to true for times ranging from 09.09.2020 00:00 up until 09.0 ...

Changing a numeric string into a number within an Angular 2 application

Looking for advice on comparing Angular 2 expressions. I have an array of data stored as numeric strings in my database and I need to convert them to numbers before applying a condition with ngClass for styling purposes. Any suggestions on how to perform ...

Is it possible for AJAX JSON response to return both accurate and undefined values sporadically?

In the process of developing JavaScript code to pinpoint the smallest unused number within a specified range of numbers, I encountered an issue with the AJAX request. Despite successfully retrieving all used numbers in the designated range, some undefined ...

Storing multiple entries in a single MySQL cell along with JSON data

I have numerous folders named after different series on my website. Each series folder contains its own chapters, with each chapter containing images. As my website is a manga (comic) site, I want to store the paths of these folders and images in MySQL and ...

Securing Email and Password Data in Cypress Tests

Greetings! I trust everyone is in good spirits. My dilemma lies in the fact that I am hesitant to include email and passwords in version control. I am considering using environment variables in my cypress tests and utilizing secrets for runtime value pro ...

Create a three-dimensional tree array in Typescript/Javascript by transforming a flat array

Received data is structured as follows: const worldMap = [ { "name": "Germany", "parentId": null, "type": "Country", "value": "country:unique:key:1234", "id&qu ...

Traverse JSON object as a string

I'm new to working with JavaScript. I have a JSON string that was created using the Google Gson API, and I'm passing this string to a JavaScript function. The JSON string looks like this: '{"validationCode":"V10291","caseNumber":"2010CF1010 ...

The module could not be found: Issue arises when trying to require a CSS file within a directive but the file or directory cannot be resolved

Following an angular+webpack tutorial, a new folder named "directives" was created. Inside this folder, a custom directive called 'kcdHello' was declared as shown below: export default ngModule => { ngModule.directive('kcdHello' ...

Issue arises when trying to implement sidebar navigation in Angular with Materialize CSS

Just starting my Angular journey and running into some trouble trying to set up a practical and responsive menu using SidebarNav and Dropdown. I used CLI to install and configure angular2-materialize and materialize-css. To create the menu, I made a comp ...

Encountering ENOENT error with Node.js file preview

I am attempting to utilize the filepreview tool to extract an image from a docx document. I have successfully installed it using the command npm install filepreview. This is the code snippet I am working with: const filepreview = require('fileprevie ...

What is the best way to invoke a TypeScript function within a jQuery function?

Is it possible to invoke a TypeScript function within a jQuery function? If so, what is the correct approach? Here is an example of my component.ts file: getCalendar(){ calendarOptions:Object = { height: 'parent', fixedWeekCount : ...

Setting up parameters and arguments in Vuex mutations: A guide

I am currently developing a todo list application using Vue.js, Vuex, and Firebase. The functionality of the app seems to be in working order with the Store file effectively managing the retrieval and display of entered todo items to and from Firestore. Ho ...