What is the way to create a "Table" that has horizontally wrapping rows in HTML5 and CSS3?

Presently, I am working with a table in HTML using tr and td tags. https://i.sstatic.net/MLDC0.jpg

However, as the number of rows increase vertically, I face limitations due to lack of space. My goal is for the content to overflow horizontally like this:

https://i.sstatic.net/WRYqm.jpg

What is the most effective method using HTML5/CSS to ensure that the content spills over if it extends beyond the table? Ideally, I want the width of the table to adjust based on the number of entries without having scrollbars or doubling the size at the beginning.

I suspect that the table tag in HTML may restrict my options. Is there a better way to achieve this using divs?

<table style="background:green;">
<tr><td>Name</td><td>Sport</td><td>Score</td></tr>
<tr><td>Jordan</td><td>Soccer</td><td>50</td></tr>
<tr><td>Jordan</td><td>Soccer</td><td>50</td></tr>
<tr><td>Jordan</td><td>Soccer</td><td>50</td></tr>
</table>

I have explored a flexbox approach, but encountered issues with the background filling properly once the entries exceed the first column:

https://jsfiddle.net/t0h7w2hw/

Answer №1

Kindly refer to the code example provided below:

In order to display rows in a list style on mobile devices, make sure to include the data-label attribute with each content td to indicate the column it belongs to. You can utilize CSS content:"" property to show labels before tds on mobile.

body {
  font-family: "Verdana", sans-serif;
  line-height: 1.3;
}
table {
  border: 1px solid #999;
  border-collapse: collapse;
  margin: 0;
  padding: 0;
  width: 100%;
  table-layout: fixed;
}
table caption {
  font-size: 1.6em;
  margin: .6em 0 .8em;
}
table tr {
  background: #f9f9f9;
  border: 1px solid #e0e0e0;
  padding: .4em;
}
table th,
table td {
  padding: .65em;
  text-align: center;
}
table th {
  font-size: .9em;
  letter-spacing: .08em;
  text-transform: capitalize;
}
@media screen and (max-width: 650px) {
  table {
    border: none;
    box-shadow: none;
  }
  table caption {
    font-size: 1.4em;
  }
  table thead {
    display: none;
  }
  table tbody {
    display: block;
  }
  table tr {
    border-bottom: 2px solid #e0e0e0;
    display: block;
    margin-bottom: .7em;
  }
  table td {
    border-bottom: 1px solid #e0e0e0;
    display: block;
    font-size: .85em;
    text-align: right;
  }
  table td:before {
    content: attr(data-label);
    float: left;
    font-weight: bold;
    text-transform: uppercase;
  }
  table td:last-child {
    border-bottom: 0;
  }
}
<table>
  <caption>Monthly Expenses</caption>
  <thead>
    <tr>
      <th scope="col">Category</th>
      <th scope="col">Amount</th>
      <th scope="col">Date</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td data-label="Category">Groceries</td>
      <td data-label="Amount">$200</td>
      <td data-label="Date">05/01/2022</td>
    </tr>
    <tr>
      <td data-label="Category">Utilities</td>
      <td data-label="Amount">$150</td>
      <td data-label="Date">05/15/2022</td>
    </tr>
    <tr>
      <td data-label="Category">Dining Out</td>
      <td data-label="Amount">$100</td>
      <td data-label="Date">05/25/2022</td>
    </tr>
  </tbody>
</table>

Answer №2

I appreciate all the advice, but my issue lies within using angular. The problem arises when I have a large number of rows, and there isn't enough vertical space to display them properly.

How does Angular relate to this particular issue?

[..] when I have numerous rows, the vertical layout becomes crowded. What I would prefer is for the content to overflow horizontally instead.

Tables are not equipped to provide the flexibility you require, especially in terms of controlling the height and flow of rows as columns.

[..] Is there a way to allow the content to spill over if it extends beyond the table? In scenarios where I only have 2 or 3 entries, I don't want to initially set the width to be double the normal size. I would rather adjust the table size based on the number of entries present.

One simple solution could involve dividing your rows into separate tables. Once you establish this structure, implementing CSS columns becomes straightforward.

To achieve this, enclose all these tables within a div with defined height restrictions. Apply column-* properties to the wrapping div for desired results. Experiment with column-gap, column-rule, column-span, and column-fill properties for aesthetic enhancement.

Furthermore, ensure to include break-inside: avoid on the tables to prevent them from splitting midway while transitioning to the next column.

Example Illustration:

#rowflow {
  height: 120px; max-height: 120px;
  border: 1px solid #d33; overflow: hidden;
  column-width: 200px; column-gap-width: 0px; column-fill: auto;
  column-rule: 1px solid #bbb; 
}
table { 
  font-family: sans-serif; margin-bottom: 2px;
  table-layout: fixed; width: 190px; 
}
table:first-child { column-span: all; }
table, th, td { border-collapse: collapse; border: 0px solid gray; padding: 6px; }
table, tr { break-inside: avoid; }
th, td { text-align: left; }
th:last-child, td:last-child { text-align: right; }
<div id="rowflow">
  <table><tr><th>Name</th><th>Sport</th><th>Score</th></tr></table>
  <table><tr><td>Jordan</td><td>Soccer</td><td>50</td></tr></table>
  <table><tr><td>Jordan</td><td>Soccer</td><td>50</td></tr></table>
  <table><tr><td>Jordan</td><td>Soccer</td><td>50</td></tr></table>
  <table><tr><td>Jordan</td><td>Soccer</td><td>50</td></tr></table>
</div>


In the provided illustration, the enclosing div restricts height, allowing columns to flow smoothly.

Explore this fiddle to observe the impact when adjusting window size.

[..] My aim is to avoid setting a doubled initial width but instead size the table according to the actual content without scrollbars appearing.

The wrapping div will naturally expand to full width. However, you can manipulate the overflow property to manage excess content display. Adapting the width dynamically based on content width involves JavaScript implementation, which can become complex.

Note: To implement the above approach successfully, fix the widths of tables for precise column alignment. Employ table-layout: fixed for a consistent layout.

Answer №3

There isn't a built-in feature in CSS that allows for styling HTML table elements in the way you described. I experimented with adjusting the positions of the table and containing div, but it didn't yield the desired result. As seen in the fiddle example you shared, using an HTML div element is necessary for achieving the desired layout.

Answer №4

//HTML

<div ng-app>
  <div class=" header-row">
    <div class="col">Name</div>
    <div class="col">Sports</div>
    <div class="col">Score</div>
  </div>
  <div ng-controller="TodoCtrl">
    <div class="row" ng-repeat="rows in chunkedData">
      <div class="span4" ng-repeat="item in rows">
        <span class="col">{{item.name}}</span>
        <span class="col">{{item.sport}}</span>
        <span class="col">{{item.score}}</span>
      </div>
    </div>
  </div>
</div>


//Script

function TodoCtrl($scope) {
  $scope.data = [
    {
      name : '0',
      sport: 'Cricket',
      score: 89
    },
    {
      name : '1',
      sport: 'Cricket',
      score: 89
    },
    {
      name : '2',
      sport: 'Cricket',
      score: 89
    },
    {
      name : '3',
      sport: 'Cricket',
      score: 89
    },
    {
      name : '4',
      sport: 'Cricket',
      score: 89
    },
    {
      name : '5',
      sport: 'Cricket',
      score: 89
    },
    {
      name : '6',
      sport: 'Cricket',
      score: 89
    }
  ];
  $scope.chunkedData = chunk($scope.data, 3);
  function chunk(arr, size) {
    var newArr = [];
    for (var i=0; i<arr.length; i+=size) {
      newArr.push(arr.slice(i, i+size));
    }
    return newArr;
  }
}

//CSS

.col{
  display: inline-block;
  width:70px;
  float: left;
  padding: 3px;
}
.header-row{
  width: 100%;
  background-color: #000;
  color: #fff;
  overflow: hidden;
  padding: 3px;
}
.row{
  overflow: hidden;
  display: inline-block;
  float: left; 
  border: 1px solid grey;
}

Check out the JsFiddle Link here

In order to display a chunk of records in the first column, you can create this chunk within the controller and then use ng-repeat to render it accordingly

Answer №5

Creating multi-column layout with div and column

.columns {
  column-count: 2;
  column-gap: 10px;
}
.myTable {
  display: table;
  width: 100%;
  height: 200px;
}
.myHeader {
  width: 100%;
  font-weight: bold;
}
.myCell {
  display: table-cell;
  width: 33%;
  float: left;
}
<div class="columns">
  <div class="myTable">
    <div class="myHeader">
      <div class="myCell">Name</div>
      <div class="myCell">Sport</div>
      <div class="myCell">Score</div>
    </div>
    <div class="myCell">Bob</div>
    <div class="myCell">Soccer</div>
    <div class="myCell">8</div>
    <div class="myCell">Jane</div>
    <div class="myCell">Softball</div>
    <div class="myCell">9</div>
    <div class="myCell">Hank</div>
    <div class="myCell">Baseball</div>
    <div class="myCell">6</div>
    <div class="myCell">Lisa</div>
    <div class="myCell">Soccer</div>
    <div class="myCell">9</div>
    <div class="myCell">Bill</div>
    <div class="myCell">Football</div>
    <div class="myCell">4</div>
  </div>
</div>

FIDDLE

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

JavaScript/TypeScript Asynchronous Filtering on AsyncIterable<T>

I am currently working with an AsyncIterable variable and I am trying to apply a filter on it. Take a look at the example below (pseudo code) - class SomeClass { private SOME_CONST= "ABCDE"; private async someFunction(): Promise<strin ...

Identifying the Click Event Within an ngx Bootstrap Modal

I recently set up an ngx bootstrap modal using the instructions provided in this helpful guide - . However, I'm facing a challenge in detecting click events within the modal body once it's open. Below is the code snippet from my app component. D ...

Guide to getting Material-UI Dialog up and running smoothly in your React application

I'm currently working on a project using material-UI, and I'm having trouble with the Dialog component not working properly. Despite trying various solutions, I haven't been able to get it to function correctly in my React application with m ...

Unable to modify form within HTML modal

I am currently facing an issue with editing bootstrap forms. I have set a default and a placeholder value via js, however, the users are unable to change the textfield values. Below is the code for my modal. getData(){ // Pulls data from our API ...

What are the best techniques for optimizing loops when inserting data into a database?

Hi there! Currently, I am facing a challenge in inserting data from an XML file into my MySql database using Sails.js and waterline for the queries. In my database schema, I have two tables named Users and Pets. A user can have multiple pets, and a pet can ...

Issue encountered in Wicket Ajax Error Log: ERROR: The listener for the "click" event cannot be bound to the "AjaxCheckBox" element as it is not present in the Document Object Model (DOM)

When running my program, I am trying to dynamically add Panels to the main page and utilize "setVisible(boolean)" functionality. However, I am encountering an error: ERROR: Cannot bind a listener for event "click" on element "institutCheck7" because the ...

Implement a recursive approach to dynamically generate React components on-the-fly based on a JSON input

My goal is to develop a feature similar to Wix that allows users to drag and drop widgets while adjusting their properties to create unique layouts. To achieve this, I store the widgets as nested JSON documents which I intend to use in dynamically creating ...

Positioning divs around a circle can be quite challenging

Among my collection of divs with various classes and multiple child divs representing guests at a table, each main div symbolizes a specific restaurant table type. I have created a jsfiddle for demonstration. http://jsfiddle.net/rkqBD/ In the provided ex ...

Perform CSS transitions simultaneously

Hey there! I'm currently working on a button that includes a Font Awesome icon at the end of it. To display the icon, I'm using the :after pseudo-element on the button, which is working fine so far. The issue I'm facing is with the CSS tran ...

Disabling the search function when it is clicked (before any actions are taken)

I've recently implemented a search form on my website, where the search field opens up upon clicking the search icon.https://i.stack.imgur.com/UeErx.png To make the search icon clickable, I disabled the search function. var $searchBtn = $search.find ...

Centrally aligning elements within a responsive row using Bootstrap's adaptive row class

I have a variety of elements on my page that need to be displayed in straight columns, with multiple images aligned horizontally and vertically. Each image has the same size and when clicked, an icon menu with three items appears in its place. As the numb ...

tips for placing an input field and button side by side

Is there a way to align the input and button on the same line using Bootstrap 5? I've tried various methods but nothing seems to be working. Any suggestions on how to style it or utilize specific Bootstrap 5 markup? <link href="https://cdn.jsd ...

Issue with managing timezones in Angular with CDT/CST offsets

I have a date in UTC format that I need to convert to CST. It is 5 hours ahead of UTC during CDT and 6 hours ahead during CTC. The UTC date is '2016-09-07T05:00:00Z' <body> <div ng-app="myApp" ng-controller="datCtrl"> <p>Da ...

Disable responsiveness for low-resolution devices

Is there a way to disable responsive design on small resolution devices? The responsive layout appears distorted when accessed on a phone. See screenshots for more details. Phone Desktop ...

Is it possible to open an image using the tag "a"?

When building my webpage, I opted to utilize webpack. In order to display multiple images on the page, I sought out a library called "lightbox2" online. This particular library allows for image popups when clicked and comes with a simple example: <a ...

Shifting the data label on a pie chart in ApexCharts - what's the trick?

I need help adjusting my data labels to make them more readable by moving them inward. It would be perfect if there is a way to dynamically center them within the slice. https://i.stack.imgur.com/bCelP.png Despite reading the documentation and trying dif ...

How to Re-run an External JavaScript File when React Conditional is updated?

Kindly review the complete question before providing an answer. I am currently working with a vanilla javascript file to trigger a fetch request upon pressing a button in a separate react file. The vanilla javascript file is located outside the src folder ...

Preserve StepContent information within Material-ui Stepper during updates to the active step

I have a Stepper component with multiple steps, each containing several TextFields. The issue is that material-ui unmounts the step contents when you switch steps, causing all the data in the TextFields to be lost. My question is: Is there a way to prese ...

What is the process for executing JavaScript in a secondary thread in V8?

In the v8 engine, JavaScript code is only able to run in the main thread. My goal is to run JavaScript code in a non-main thread so that CPU-intensive tasks cannot interrupt the CPU time of the main thread. However, I am currently at a loss on how to accom ...

Challenges of positioning two div elements next to each other without adhering to the width of the container

Apologies for my limited knowledge of CSS and HTML; I am relatively new to this. I have gone through various questions and tutorials on how to align two divs side by side, but I seem to be facing difficulties in controlling the width of the divs in my cod ...