Styling with CSS to format a table so that each cell occupies one row when viewed on narrower

I've come across some HTML that resembles this structure

<html><body><table>
  <thead><tr><th>A</th><th>B</th><th>C</th><th>D</th><th>E</th></tr></thead>
  <tbody>
    <tr><td>1A</td><td>1B</td><td>1C</td><td>1D</td><td>1E</td></tr>
    <tr><td>2A</td><td>2B</td><td>2C</td><td>2D</td><td>2E</td></tr>
    <tr><td>3A</td><td>3B</td><td>3C</td><td>3D</td><td>3E</td></tr>
  </tbody>
</table></body></html>

Each row represents an object, with columns representing its properties. The cell values can be quite lengthy, sometimes up to 20-30 characters long. While it displays well on most devices, smaller phones may pose a problem. While I could hide certain columns on narrow devices, it doesn't feel like the right approach in this case. Currently, I have x-overflow: scroll applied to the table, but I would prefer a CSS solution that restructures the table for narrow screens as follows:

A: 1A
B: 1B
C: 1C
D: 1D
E: 1E
-----
A: 2A
B: 2B
C: 2C
D: 2D
E: 2E
-----
(etc)

Assuming I want to implement this unconditionally without device width testing, tweaking the HTML markup slightly is acceptable to add extra classes or attributes. It's important to keep using a <table> element with one <tr> per logical row due to backward compatibility reasons. Despite the availability of a cleaner API, many users still scrape the site. As a result of internal dynamics, I'd rather avoid a JavaScript solution if possible (although I'm capable of writing one if necessary).

While I've made progress with my current CSS, particularly in styling the data rows, I'm unsure how to dynamically generate the field names which are currently fixed as 'X' in my code snippet:

  thead { display: none; }
  table, tr, td { display: block; }
  tr + tr { border-top: thin solid black; }
  td::before { content: "X:"; display: inline-block; width: 2em; }

I've noticed similar designs on various websites, but finding a CSS-specific implementation has proved challenging. While this seems like a common requirement, I'm struggling to locate suitable resources or explanations due to search term ambiguity.

Answer №1

Keep going, you're almost there! Consider using data-col attributes on your <td> elements and referencing them in your CSS using the content property with :before

thead {
  display: none;
}

table,
tr,
td {
  display: block;
}

tr+tr {
  border-top: thin solid black;
}

td::before {
  content: attr(data-col)':';
  display: inline-block;
  width: 2em;
}
<table>
  <thead>
    <tr>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
      <th>E</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td data-col="A">1A</td>
      <td data-col="B">1B</td>
      <td data-col="C">1C</td>
      <td data-col="D">1D</td>
      <td data-col="E">1E</td>
    </tr>
    <tr>
      <td data-col="A">2A</td>
      <td data-col="B">2B</td>
      <td data-col="C">2C</td>
      <td data-col="D">2D</td>
      <td data-col="E">2E</td>
    </tr>
    <tr>
      <td data-col="A">3A</td>
      <td data-col="B">3B</td>
      <td data-col="C">3C</td>
      <td data-col="D">3D</td>
      <td data-col="E">3E</td>
    </tr>
  </tbody>
</table>

An alternative method involves utilizing CSS variables to store column values, which can make your code less repetitive and save space for longer tables:

thead {
  display: none;
}

table,
tr,
td {
  display: block;
}

tr+tr {
  border-top: thin solid black;
}

td:before {
  display: inline-block;
  width: 2em;
}

td:nth-child(1):before {
  content: var(--col1)':';
}

td:nth-child(2):before {
  content: var(--col2)':';
}

td:nth-child(3):before {
  content: var(--col3)':';
}

td:nth-child(4):before {
  content: var(--col4)':';
}

td:nth-child(5):before {
  content: var(--col5)':';
}
<table style="--col1:'A'; --col2:'B'; --col3:'C'; --col4:'D'; --col5:'E'">
  <thead>
    <tr>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
      <th>E</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1A</td>
      <td>1B</td>
      <td>1C</td>
      <td>1D</td>
      <td>1E</td>
    </tr>
    <tr>
      <td>2A</td>
      <td>2B</td>
      <td>2C</td>
      <td>2D</td>
      <td>2E</td>
    </tr>
    <tr>
      <td>3A</td>
      <td>3B</td>
      <td>3C</td>
      <td>3D</td>
      <td>3E</td>
    </tr>
  </tbody>
</table>

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

What is the best way to incorporate a variety of colors into a single element?

Using a combination of colors in one element I'm looking for ways to incorporate multiple colors into a single element effectively. My initial attempt with the color mix function didn't work as expected, so I need new ideas and techniques on how ...

Converting JSON to HTML is like translating a digital language

I am in the process of developing a web application, and I have implemented an ajax request that queries a database (or database cache) and returns a large JSON object. Since I am new to working with JSON, when my PHP script retrieves data from the databas ...

How can I dynamically populate a select menu in HTML without the need to submit any data

Looking for help with an input form in HTML that uses a combination of input and select boxes. My goal is to dynamically populate a select menu based on the data entered into the input boxes. For example: Employee One: Jim Employee Two: John Employee Thre ...

The range slider's color value is not resetting correctly when using the <input>

Before repositioning, the slider is at this location: (both thumb and color are correctly positioned) https://i.stack.imgur.com/J3EGX.png Prior to Reset: Html <input id="xyzslider" class="mdl-slider mdl-js-slider" type="range" min="0.0" max="1.0" va ...

Adjusting the background color using CSS according to the browser's dimensions

I'm having trouble identifying the issue with this code. The background color remains white and doesn't change as expected. <style type="text/css"> h1 { position: absolute; text-align: center; width: 100%; ...

Ensure that the text is wrapped properly when implementing innerHTML functionality

Within my Angular 5 application, I am faced with a requirement to display HTML content retrieved from a database. An example of the text stored in the database is: <div><u>Documents and Files</u></div><ul><li>These docu ...

Optimizing Bootstrap for Tablet Browsing in Internet Explorer

Hey there, I have a question regarding Internet Explorer and tablets. As I revamp this website and integrate Bootstrap into it, my focus is currently on the small-sized IE browser for tablets. My dilemma arises from not knowing if there are any tablets th ...

Challenges with moving images in Unslider

There seems to be an issue with the unslider-arrows on the unslider banner. The images are not sliding properly when transitioning to the next image without user input. Instead, they resize from small to full size starting at the top of the .banner div. ...

JavaScript decimal precision function malfunctioning with currency format conversion

My current snippet works perfectly with the currency format 249.00, but I need to adapt it for a site that uses euros with pricing in the format 249,00. When I make this change, the total calculation goes haywire and shows as 29.900,00. Can someone advise ...

Leveraging ASP.NET MVC 5 to integrate an online document viewer from Office 365, seamlessly displaying Word documents within a sleek, compact window

We have been struggling to showcase a Word document (.docx) within an iframe on our website using the Office 365 service. The document is stored in One-Drive for business online and has been appropriately shared. After signing in, we obtained a link to the ...

Jumping CSS dropdown menu glitch

I'm facing an issue with a dropdown menu. The main problem is that the "parent" link is moving when hovered over. HTML: <ul id="nav"> <li><span>Page 1</span> <ul> <li><a>Extralong Pag ...

Following an update, Storybook is failing to apply JSX styles

After upgrading my project from NextJS 10 to NextJS 12, everything is functioning normally except for Storybook, which is now missing its styles. I utilize the styled-jsx library to create embedded css, implementing it in this way: const SearchResult = ({ ...

Tips for showcasing a table generated from various input types on a separate page after pressing the submit button

After creating two JavaScript functions, I am eager to utilize both of them upon pressing the submit button on my form. The first function is already integrated into the submit button and activates a paragraph display upon submission. Now, I intend to sh ...

Animations experiencing delays on mobile Chrome

I am currently exploring the world of website animations. I have a version of the jsfiddle code linked below that is similar to what I am working on. The animations function perfectly when viewed on desktop, but when accessed on mobile - specifically on my ...

Is it possible to meta-refresh a page for redirection?

When creating a webpage, I included a META tag like this: <META http-equiv="refresh" content="5;URL=http://www.google.com"> The issue is that mobile browsers do not support this meta tag. It redirects properly on web browsers, but not on mobile dev ...

Guide for Sending a Textnode from One Page to a Different Page within a Specific Id Element through PHP

firstpage.html : <body> <?php $text = $_POST['text']; ?> <p style = "color:red; " id = "getext"><?php echo $text; ?></p> </body> secondpage.php : <body> <?php $text = $_POST['text']; ?> ...

What is the best way to position the underline to appear beneath the second line in mobile view?

I have successfully incorporated a code to add a blue underline to the company name. However, in mobile view, the blue line appears on the first line. How can I adjust it so that it starts from the second line? Below is my CSS code: label { margin: 0; ...

Designing templates for websites and applications using node.js

Simplified Question: As I delve into improving my skills with node.js, I'm exploring the concept of templating. How would using node to serve one HTML file and loading page-specific information through AJAX/sockets impact performance and design princ ...

Python: HTML regex not finding a match

This is the code snippet I am struggling with: reg = re.search('<div class="col result_name">(.*)</div>', html) print 'Value is', reg.group() The variable 'html' holds content like this: <div class="c ...

Create a visually stunning CSS3 animation within a specified container, mimicking the style shown in the

I'm currently working on creating the animation depicted in the image below: https://i.stack.imgur.com/W69EQ.jpg My goal is to develop a video slider where, upon clicking a button, the video will seamlessly shift to the right within its parent conta ...