Limiting the number of rows in an HTML table: a comprehensive guide

Need help with displaying item names in a table with a limit of three rows. If there are more than 3 items, the 4th item should move to the second column, and if there are more than 6 items, the 7th item should go in the third column. Currently, I am using a regular table for this.

<table>
    <tr *ngFor="let item of group">
        <td>{{item}}</td>
    </tr>
</table>

I need assistance determining the condition necessary to limit the number of rows and appropriately place them into columns based on the number of items. Any guidance would be appreciated!

Answer №1

If you're looking to arrange a layout using CSS Grid, the key is utilizing grid-auto-flow. To help you get started, here are some helpful resources:

Below is an example of a layout created using Grid with explanatory annotations:

.table {
  display: grid;
  grid-auto-flow: column; /* items fill grid container by column */
  grid-template-rows: repeat(3, 1fr); /* max 3 rows equal height */
  gap: 0.125rem;
}

.table > div {
  background-color:teal;
  padding: 0.5rem 1rem;
}
<div class="table">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
</div>

Answer №2

@Eve has provided a solution to this problem using CSS techniques.

For those interested in manually manipulating the data, here is a step-by-step guide:

export class MembersComponent {
  // Data values
  team: Array<string> = ['X', 'Y', 'Z'];
  // Set number of desired rows
  rows: number = 2;
  // Calculate columns based on data length and specified row count
  columns: number = Math.ceil(this.team.length / this.rows);

  // Store transformed data here
  information: any = [];

  constructor() {
    // Counter for tracking data
    let index = 0;
    // Outer loop
    for (let k = 0; k < this.columns; ++k) {
      // Create a new row within data array
      this.information.push([]);
      // Inner Loop
      for (let l = 0; l < this.rows; ++l) {
        // Avoid adding undefined elements
        if (this.team[index]) {
          this.information[k][j] = this.team[index];
        }
        // Update counter
        index++;
      }
    }
    // Transpose the data for proper display
    this.information = this.transpose(this.information);
    console.log(this.information);
  }

  // Source: https://stackoverflow.com/questions/17428587/transposing-a-2d-array-in-javascript
  transpose(array: any) {
    return array[0].map((col: any, i: any) =>
      array.map((row: any) => row[i])
    );
  }
}

With the data now organized into a 2D format with correct rows and columns, you can render it in your HTML as shown below:

<table class="table">
  <tr *ngFor="let line of information">
    <span *ngFor="let col of line">
      <td *ngIf="col">{{ col }}</td>
    </span>
  </tr>
</table>

You have the flexibility to adjust the order in which elements appear within each row by modifying the loops in the code. Additionally, feel free to experiment with varying row counts and dataset sizes for further testing.

See a demo here https://stackblitz.com/edit/angular-cre8iv?file=src%2Fmembers%2Fmembers.component.ts

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

Creating an inline list with icons aligned using Bootstrap4

I have a list where some words span two lines, but the second line jumps under the icons at the bottom. How can I keep both lines next to the icon? I'm using Bootstrap and chose to use the list-inline class. Maybe using columns for this list would wor ...

"Utilizing Ionic 3 for navigating internal links within a website using the tag

Hello everyone, I recently started exploring Ionic and Angular and I have a question regarding internal links in the Ionic framework. To begin my learning journey, I decided to work with the pre-made project called Ionic sidemenu. I am attempting to create ...

How can I insert a item into an Array using JavaScript code?

My instructor set up an array in my JavaScript file that is off limits for me to modify. My task is to add new objects to it through code without directly manipulating the existing array. Here's a snapshot of what my array contains: const words = [{ ...

Responsive HTML code for a textarea, button, and table

I'm currently developing a website that includes a textarea, button, and table within the body content. The responsiveness of my content works well, except for extremely narrow displays such as mobile phones. In such cases, the table does not wrap pr ...

Use RXJS to prevent having multiple nested subscriptions

I am looking to revamp the code snippet below: this.dataUserSubscription = this.store$.pipe(select(selectUser)).subscribe( user => { this.store$.pipe(select(selectUserData, {user}), take(1)) .subscribe(u ...

I'm currently experiencing a challenge with a project I'm tackling that specifically deals with chart.js

In my recent coding project, I created a script to gather user input and then present it in various chart formats. However, upon executing the code, the selected chart fails to display after inputting values and clicking on the "generate chart" button. Her ...

Tips for establishing breakpoints within Material UI grid for achieving responsiveness

I am currently utilizing Material ui's Grid component to organize my user interface elements. Here is the code snippet: <Grid container spacing={3}> <Grid container item xs={12} sm={12} md={12} style={{ marginTop: '-1.5%', marginRi ...

Implementing an onClick event to reveal a concealed div located above each bar in D3.js (potentially requiring additional CSS code)

I'm currently working on a project where I want a hidden div, named myDiv, to be displayed above the clicked bar whenever a square bar is clicked. Here's what I've attempted so far: 1) I have written a Javascript function called showDiv() ...

Guide to highlighting input field text using Angular

I've set up an angular page that includes an input field within its template. My goal is to highlight the text in the input field when a specific function is triggered. When I refer to "highlighting the text," I mean (check out the image below) https ...

Align two text elements of varying heights at the center of a container

I need to style a fixed-height container with a width of 100% that is set to display:block. Inside this container, there are two text elements styled differently in terms of font-size, and floated left and right respectively. Here's the HTML structu ...

Position the select tag adjacent to the textbox

Looking for assistance on how to arrange the <select> tag beside the "Desired Email Address" field within my email registration form. I believe a modification to the CSS code is necessary. Below you will find the HTML and CSS (snippet) related to th ...

"Discover the magic of creating a navigation menu with jQuery toggle - let me show

Recently, I managed to create a side navigation using the target function in CSS3. However, I am curious about how I can achieve the same result using jQuery without disrupting the layout. Any assistance would be greatly appreciated. Here is the code sni ...

Creating an image button within a form using Twitter Bootstrap

My current situation involves having images like this: <img src="image1.jpg" width="80" height="80" id = "wp" alt="workplace"> <img src = "image2.jpg" width="80" id = "tm" height="80" alt="team"> and then writing the onclick event for ...

Creating a radial gradient texture using CSS

I'm encountering an issue with my radial gradient and texture combination. Here is the code snippet I am using: background-image: url('../img/texture.png'); /* fallback */ background: -moz-radial-gradient(rgba(253,253,253,0.1) 0%, rgba(2 ...

The functionality of the angularjs class seems to be malfunctioning

I'm a new learner of angularjs and I've created a simple page below. I have a style called "item" that I'm trying to apply to a div, but it's not working. However, if I use inline style, then it works fine. Can someone please help me f ...

Rotating images on a canvas

We're currently implementing Ionic and Angular in our project. One issue we are facing is regarding image rotation on canvas. When we click on an image, the rotation works perfectly if it's a jpg file. However, when we pass a base64 image, the r ...

Angular Material Slide-Toggle Takes Too Long to React

In my project, I am facing an issue with a control panel that contains an Angular Mat-Slide-Toggle element. Here is the code snippet: <mat-slide-toggle (change)="onQAStateDisplayChanged($event)">Display QA Status</mat-slide-toggle> When the c ...

When using Vue with CSS3, placing an absolute positioned element within a relative wrapper can cause issues with maintaining the

Just starting out with Vue and diving into the world of CSS3! I'm currently working on a component that you can check out here: https://codesandbox.io/s/yjp674ppxj In essence, I have a ul element with relative positioning, followed by a series of di ...

Customized figcaption formatting separate from the surrounding text

Is there a way to add a "figcaption" with independent settings to images placed alongside paragraphs in HTML? I have the following code snippet, but I'm unsure if I am using the figcaption tag correctly: <p><figure><span class="image ...

Adjust the size of fonts for elements that are added dynamically

My goal is to dynamically add elements with decreasing font sizes to a fixed-width/height container until they no longer fit. I've managed to scale the font based on the browser window size, but that's not the intended solution. Is it possible t ...