Tips for correctly sizing and centering a DataTables table on a computer screen while ensuring that the header and data cells remain aligned

I have implemented a DataTables-enhanced HTML table for sorting and horizontal scrolling on tablets and mobile devices, which works well on smaller viewports.

However, I am encountering issues with the desktop viewport:

On desktop, my goal for the table is to:

  1. Fit within its container with a maximum width of 1300px,
  2. Be centered horizontally on the screen,
  3. Avoid horizontal scrolling,
  4. Ensure that column widths are not excessively large, adjusting according to the longest value in each column purposefully.

Whenever I try to set the table’s width and center it manually, I face one of two problems:

  • The table header (thead) becomes misaligned, appearing offset to the left, while the body of the table (tbody) is centered.
  • Both the header and body of the table are centered, but the column widths do not match between them, causing alignment issues and confusion.

How can I ensure that the table header and data cells remain properly aligned while achieving the desired styling and layout on the desktop viewport, considering the setup already functioning correctly on smaller viewports?

Here is my current setup:

HTML table:

<div class="table-container-byty" style="width: 100%;">
    <table class="custom-byty-table display" style="width: 100%;">
        <thead>
            <tr>
                <th>Unit Label</th>
                <th>Floor</th>
                <th>Number of Rooms</th>
                <th>Building</th>
                <th>Unit Area</th>
                <th>Balcony Area</th>
                <th>Total Area</th>
                <th>Price</th>
                <th>Unit Status</th>
                <th>View Unit</th>
            </tr>
        </thead>
        <tbody>
            // Table rows content here
        </tbody>
    </table>
</div>

jQuery Datatables initialization JavaScript at the end of <body> tag:

// JavaScript code here

CSS:

// CSS styles here

Answer №1

To ensure that your table is responsive, you can follow these steps:

First, set the width of the container to 1300px and then apply a max-width to the table.

Here is a possible CSS fix with comments for explanation:

.table-container-byty {
  width: 1300px !important; /* Set the maximum width */
  max-width: 100% !important; /* Allow it to shrink based on available space */
  margin: auto; /* Optional */
}
.table-container-byty table { /* Select only the tables within the container */
  font-weight: bold;
  max-width: 100%; /* Ensure it adjusts to available space */
}

Another potential solution mentioned in the comments below: https://codepen.io/gc-nomade/pen/RNbRxxz

jQuery(document).ready(function() {
  // Calculate the height of the sticky menu bar
  const menuBarHeight = jQuery('#menu-bar-rlp').outerHeight();

  // Determine the header offset based on screen size
  let headerOffset = menuBarHeight; // Default for tablet/mobile
  if (window.innerWidth > 1024) { // For desktop (screens wider than 1024px)
    headerOffset = menuBarHeight + 30; // Add extra space for desktop
  }

  // Initialize DataTable
  jQuery('.custom-byty-table').DataTable({
    responsive: false,
    sScrollX: '100%',
    sScrollXInner: '100%',
    bScrollCollapse: true,
    paging: false,
    searching: false,
    ordering: true,
    info: true,
    autoWidth: true,
    fixedHeader: {
      header: true,
      headerOffset: headerOffset
    },
    dom: 'frtiS',
    deferRender: true
  });
});
.table-container-byty {
  width: 1300px !important;
  max-width: 100% !important;
  margin: auto;
}

.table-container-byty table {
  font-weight: bold;
  max-width: 100%;
  min-width: 600px;
  table-layout: fixed;
}

* {
  box-sizing: border-box;
}

.table-container-byty table tr>* {
  text-overflow: ellipsis;
  overflow: hidden;
}

<!-- Custom styling for the table -->
...

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js"></script>
<div class="table-container-byty" style="width: 100%;">
  <table class="custom-byty-table display" style="width: 100%;">
     ...
  </table>
</div>

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

Calculate the total rows within a specified date range

Within my database, there is a column named IsStaff, which returns a value as a bit. This signifies whether a staff member in a company has an illness (1) or not (0). How can I construct an SQL query to count the occurrences of both 1's and 0's w ...

The process of retrieving CSS attributes from a control found by XPath using Selenium IDE

During my Selenium IDE script execution, I am looking to identify and handle an error state. This specific error state is visually highlighted on the page with a select control changing its background color to a light shade of red. The xpath for the selec ...

Something went awry when I tried to divide the HTML and CSS code

<div class="col-md-12" style=""> <div class="col-md-4 linkdetail" class="cursor"> <div class="col-md-12" style="margin-bottom:40px"> <img src="/img/product3.png" style="display:inline-block;width:100%;"> </div ...

Is there a way to partially conceal the H2 text using CSS?

Is there a way to partially hide H2 text using CSS? I have the following code: HTML: <div class="twocol-box1 superflex-content-6-12"> <h2 data-content="My - Text&amp;nbsp;<span style=&quot;float:right;&quot;>M ...

What is the best way to execute an asynchronous request in AngularJs and Typescript?

Despite its simplicity, I can't seem to find an answer to this question as I am relatively new to Javascript, Typescript, and Angular. I have searched extensively without success. My objective is to send a basic request to a server and handle the res ...

Exploring Angular's Animation Feature for HTML Element Movement

I'm currently using @angular/animations module to animate HTML objects and I want to move an object when a button is clicked. For example: * The object initially has top: 800px, left: 800px * Clicking the 'W' button should move the obje ...

Hover over an element to trigger the background fading effect on the parent div

I'm looking to create a hover effect on an element within a fullscreen div. When I hover over the element, I want a background image to fade in on the div with the class ".section." While I can easily display the background image, I am unsure of how t ...

Using HTML5 and CSS transitions to scale an image within a 960 grid layout

Having some trouble achieving a smooth transition for the height and width of images on my webpage. I believe if you take a look at my page, not much explanation is needed: Click here to see the image transition The goal is to enlarge the image to double ...

Steps for dealing with uncaught exceptions in react and displaying a straightforward "internal error" notice on the user interface

When working on the node side, // Handling uncaught exceptions with Node.js process.on('uncaughtException', (error, source) => { fs.writeSync(process.stderr.fd, error, source); }); How can we achieve similar functionality in React for the ...

Complete layout photography using bootstrap 4

I'm looking to create a banner that adjusts appropriately for mobile and desktop display. Here's what I've tried: When it is displayed in mobile When it is displayed in desktop In my attempt, the text alignment was off even though I used ...

Ending a session in JavaScript using session_destroy()

I am seeking a JavaScript code that can automatically end the session of inactive users on a live chat website. The website tracks user activity every 5 minutes and updates the database with a timestamp of their last activity. For example, if a user has n ...

The bubble dialogue box in my picture

Looking to create a panel with images that, when clicked on, display an info window similar to Google Map's pin maker. When you click on an image, a balloon should appear containing additional information. Check out this example <a id="infowindow ...

Display the remainder of an image's height within a div container

Here is the code snippet I am working with: HTML: <div id="mapWrapper" style="height: 624px;"> <div class="box" id="map"> <h1>Campus</h1> <p>Description Campus Map.</p> <img src="abc.png" ...

Rails question: What is the best method to link a stylesheet to a layout?

I have implemented a controller in my application that utilizes a custom layout named "special": class SessionsController < ApplicationController layout "special" ... end To complement this, I have created a new layouts/special.html.erb file: < ...

Retrieving precise information from a Json file with PHP

Hey there, I have a JSON file and I'm looking to extract certain data from it. Here's how the file appears: { "took" : 1, "timed_out" : false, "_shards" : { "total" : 1, "successful" : 1, "skipped" : 0, "failed" : 0 }, ...

Toggle the sidebars to slide out and expand the content division using JavaScript

I am looking to achieve a smooth sliding out effect for my sidebars while expanding the width of the middle content div. I want this action to be toggled back to its original state with another click. Here's what I've attempted so far: $(' ...

Having trouble passing $scope, $route, or $http in your AngularJS factory functions?

Why does my factory keep throwing an error when the $scope, $route, $http are present? app.factory("factoryContacts",function($scope,$route,$http){ return { getContacts: function(){ return $http({ me ...

Apply CSS to a dynamically generated class

My system allows users to create multiple unordered lists (<ul>) with custom class names pulled from a database. Users can add or delete these lists and assign a color to each one. While I can save the color information in the database, I am unsure h ...

Interactive website that transitions to a fresh page as we scroll further

As a beginner in web design, I've noticed a trend of companies using websites that automatically transition to the next page when scrolling down. An example of this is . What is this type of template called and are there any open source designs availa ...

What is the best way to remove the white dots that are showing up next to my Navbar links on a bootstrap template?

I've been utilizing this template from ShareBootstrap and it has been running smoothly, except for one pesky issue: Mysterious white dots that are labeled as li.nav-tem::marker keep showing up about an inch to the left of each Navbar link. Here is so ...