Creating a table that adjusts its columns to match the same width percentages for a responsive design

Three tables were created with identical column names. The HTML markup for each table is consistent. When viewed on a laptop browser, the tables display correctly as depicted in this screenshot:

https://i.sstatic.net/5BAdg.png

However, when viewed on a smaller screen (mobile device), the widths of the tables are distorted:

https://i.sstatic.net/8coWv.png

The issue arises because the second and third tables have longer column names compared to the first table. How can I ensure that all tables have the same width when viewed on a mobile phone? What CSS code do I need to achieve this? Thank you in advance for your help.

The code snippet is provided below:

table {
  border-collapse: collapse;
  border-spacing: 0;
  width: 100%;
  border: 1px solid #ddd;
}
th,
td {
  text-align: left;
  padding: 8px;
}
tr:nth-child(even) {
  background-color: #f2f2f2
}
<div style="overflow-x:auto;">
  <table>
    <tr>
      <th style="width: 15%">First Name</th>
      <th style="width: 15%">Last Name</th>
      <th style="width: 7%">Points</th>
      ...

Answer №1

The problem arises from the use of percentage-based width.

 <th style="width: 15%">Points</th>

Due to different screen sizes, a percentage value will result in varying absolute widths. To maintain consistency across all screens, it's recommended to set a fixed value instead.

 <th style="width: 10rem">Points</th>

Please note that the choice of 10rem is arbitrary and requires experimentation.

This is because percentage-based width cascades down. The table width relies on screen size, influencing cell widths as well.

You can also establish a minimum width to lock it at, for example, 10rem but allow growth up to 15% of the table's width beyond that.

table {
  width: 100%;
}
th {
  min-width: 10rem;
  width: 15%;
}
td, th {
  border: 1px solid;
}
<table>
  <tbody>
    <tr>
      <th>first</th>
      <td>a</td>
      <td>b</td>
      <td>c</td>
      <td>b</td>
      <td>d</td>
    </tr>
    <tr>
      <th>second</th>
      <td>a</td>
      <td>b</td>
      <td>c</td>
      <td>b</td>
      <td>d</td>
    </tr>
    <tr>
      <th>third</th>
      <td>a</td>
      <td>b</td>
      <td>c</td>
      <td>b</td>
      <td>d</td>
    </tr>
  </tbody>
</table>

Answer №2

First and foremost, it is advisable not to embed styles directly in the HTML elements. It would be more efficient to create a separate CSS file and link it to your HTML page, or include all CSS within the header section. Take a look at the sample codes below, make necessary adjustments, and consider using media queries for different screen sizes.

Don't forget to include this meta tag:

<meta name="viewport" content="width=device-width, initial-scale=1.0">

Next, define the styles in the header:

<style type="text/css">
    .table-header{
        min-width: 80px;
        text-align: left;

    }
    .tables {
        width: 100%;
        margin-bottom: 30px;
    }
</style>

After that, apply the CSS classes to tables and table headers:

<table class="tables">

    <tr>
  <th class="table-header">First Name</th>
  <th class="table-header">Last Name</th>
  <th class="table-header">Points</th>
  <th class="table-header">Points</th>
  <th class="table-header">Points</th>
  <th class="table-header">Points</th>
  <th class="table-header">Points</th>
  <th class="table-header">Points</th>
  <th class="table-header">Points</th>
  <th class="table-header">Points</th>
  <th class="table-header">Points</th>
  <th class="table-header">Points</th>
</tr>

Lastly, note that the provided code snippet is only for a specific screen size. To ensure compatibility with various screens, utilize CSS media queries.

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

Unable to modify input box border

After setting up validation on a form and looking into previous answers, I have come across the following solution: CSS .required_field { border-style: solid; border-color: red; } Whenever a field is empty or null, I am adding the class: JavaSc ...

Efficiently incorporating styles and CSS, as well as Bootstrap CDN, into window.print() while utilizing Vue.js

I am trying to print from my Vuejs component and apply CSS and Bootstrap styles to the printed page. Currently, I am using window.print() inside the mounted lifecycle hook as shown below: export default { mounted() { ...

Reorganize elements using CSS styling

I have a trio of child divs with the classes span2, span7, and span3. When my browser width drops below 763px, I want them to display in the order span2, span3, and span7. How can I achieve this using CSS? Here is the code snippet I started with: <div ...

Using javascript and d3.js to display a set number of items on each line through printing

I'm currently working on a project that involves printing a specific number of rectangles per line using d3.js var rectangle = svgContainer.selectAll("rect").data(data).enter().append("rect") .attr("x", function(d,i){ return i*5}) ...

Retrieve the value of the option that has been selected and then send it over to the function

Hello, I am currently working on creating a reservation page using Razor Pages in ASP.NET. The page includes two drop down lists - one for selecting the location and the other for choosing a room within that specific location. I want to pass the selected l ...

Advanced CSS Techniques for Customizing UI Elements

Currently, I am incorporating Material UI Components into my react-app. When it comes to customizing the styles of these components, such as adding margin-top and font-weight to a button text, I encountered a challenge due to using CSS Modules. I resorted ...

Incorporating the 'react-day-picker' DatePickerInput in a Bootstrap Modal Interface

I am attempting to incorporate a DatePickerInput component into a bootstrap modal. I am hoping to achieve a similar look as shown on the official website here. However, when placed inside the bootstrap modal, it appears like this. My assumption is that ...

what is the best way to send file input value to a JQuery function?

How can I pass the file input value to a jQuery function, when there can be multiple files selected? Below is the code snippet I am currently working with: HTML <input id="images" name="images[]" placeholder="" class="form-control input-md" type="file ...

RAZOR - Strip image elements from variable with HTML content

In the code snippet below, I am using a helper to display content: @Html.Raw(Model.PageData.PageContent) My goal is to filter out any image tags that may be present. I have explored methods like .substring(), but they require specific indices or string n ...

Arrange the parallel table columns within their own individual divs to be perfectly aligned

I have a layout with two divs stacked on top of each other, each containing a table with the same number of columns. I need to ensure that the columns in both tables are the same width and aligned properly. If a column in one table expands, I want the corr ...

CSS slider experiencing issues

I'm currently working on creating a custom CSS ticker by referencing various examples online. I've managed to develop something that functions well, but it seems to only cycle through the initial 4 list items. Once it reaches the 4th item, it loo ...

Guide to using Python and Selenium to automate clicking the "Load More" button on the webpage "https://github.com/topics"

With just one click of the load more button, I can uncover a plethora of information and scrape additional HTML content beyond what is initially shown. In this scenario, the task at hand involves navigating to github.com/topics and locating the singular b ...

How to make the slides in a Bootstrap 4 carousel slide in and out with animation

I'm currently utilizing the bootstrap 4 carousel and have made some customizations to fit my project needs. The main requirement is: When I click on the next slide, the current next slide should become active and a new next slide should load with ...

Is there a way for the remaining divs in a column to match the width of the widest div?

I'm attempting to ensure that the divs in a column take the width of the widest element, with the exception of the top div which should span 100% of the screen. How can this particular layout be achieved? Please refer to the image below for a clear ex ...

Extracting Data from Web Pages

How can I efficiently extract data from a webpage with dynamic loading using AJAX? For instance, imagine a webpage that initially shows 20 images, but as the user scrolls down, more images are loaded (similar to Facebook). In this scenario, how would you ...

"Wordpress Pluto theme: A stellar choice for your

I'm trying to add a link in my main template.index file that will redirect to one of my pages when clicked on the JavaScript button at the top in Pluto theme. Currently, the text is there but clicking on it opens something I don't want. Here&apo ...

Is there a way to make placeholder text automatically adjust its size to fit within the text input element and display its complete content?

I am working on a piece of HTML code that includes a form with a table for traveler information. However, I am having trouble ensuring that the placeholder text remains fully visible at all times. To give you a visual example, here is what I currently hav ...

The same bootstrap column code shows varying behavior

This week, I delved into learning HTML with the goal of creating my own website using bootstrap. However, I encountered a perplexing error - code that should display two pieces of text on the same line is behaving inconsistently for seemingly identical sni ...

Deciding Between Javascript DOM and Canvas for Mobile Game Development

My idea for a mobile game involves using the Phonegap framework to create a game where players can control a ball's movement by utilizing their phone's accelerometer. I also envision incorporating other elements like enemies and walls into the ga ...

Transferring scope between pages without the need for an angular service definition

Looking to open a new JSP page while passing the $scope in order to utilize an array response generated in the initial page. Example from test.js file: (function() { 'use strict'; angular .module('test', []) .control ...