What is the best way to horizontally center my HTML tables and ensure that they all have uniform widths?

I'm currently facing an issue where I'd like to center align all tables similar to the 'Ruby Table.' However, I'm unsure of how to achieve this.

You may also observe that some tables have varying widths. What CSS rule can I apply to adjust the width of the entire table so they are consistent?

Below is my HTML code:

<!DOCTYPE html>
<html>

<head>
  <title>Personal Bests</title>
  <link rel="stylesheet" type="text/css" href="css/home.css">
  <meta charset="UTF-8">
</head>

<body>
  <main>

   <div id="section">
      <article>
        <h2>FireFalcons1 Best Times</h2>
     <p>
    Below you will find all of my best times on Time Trials Max Speed (100%) and Story Mode (100%)
    </p>
    <p class="TA">
    TIME ATTACK - MAX SPEED (100%)
      </article>
    </div>

<!--Ruby HMTL Table-->

<table class="rubyTable">
  <tr>
    <th class="rubyHeader" colspan="6">Ruby Cup</th>
  </tr>
  
  <!-- More table content here -->
  
  </table>

<!--Sapphire HMTL Table-->

  <table class="sapphireTable">
    <!-- Sapphire table content goes here-->
  </table>

<!--End of Table-->
    <hr>
    <footer>
      <strong>
                Copyright &copy; 2016 Stephen Fawcett, All rights reserved
        </strong>
    </footer>
  </main>
</body>

</html>

And here is my CSS related to 'Personal Bests':

 
/* Personal Bests CSS */
.TA {
    /* Custom styles for TA */
}

.rubyTable {
    /* Styling for Ruby Table */

}
/* Additional CSS for other tables */

.tg .tg-mzmv {
    /* Styling for specific elements */
}

Please focus only on the CSS located under the "Personal Bests CSS" comment.

Answer №1

Here is a helpful suggestion:

.amethystTable, .topazTable, .opalTable, .rubyTable, .emeraldTable {
    width: 90%;
    margin: 0 auto;
}

Answer №2

Starting off, it might be beneficial to end your

<p class="TA"> with a </p>, 

This way, you can begin testing out your CSS styles and properties.

Answer №3

To horizontally center a static block-level element in CSS, you can utilize the margin:auto; property.

.rubyTable, .sapphireTable, .diamondTable {
    /* add any necessary table class names above */
    margin:auto;
}

Please note that in this shorthand version, no top or bottom margin is specified for clarity. It is recommended to refer to the documentation on Margin and shorthand CSS syntax.

This method automatically sets the left and right margins to centrally position the object, in this case, a table. Since tables are block-level elements by default, their width is 100%. Therefore, it's advisable to also specify a width value along with the margin property for values greater than zero.

For instance, if you want to assign a specific width and margin to ALL table objects, regardless of their class, you can target the table element type in your CSS:

table {
    width:80%;
    margin:auto; 
    min-width:300px; /* for mobile screens */
}

It's important to note that the reference to "table" in the above code does not have a preceding period (.), indicating that it targets an element rather than a class rule.


Optimizing Repetition:

Upon reviewing your question, it appears that there is a significant amount of repetition in your HTML code, such as having multiple instances of the same class name like rubyData scattered throughout. You can streamline this using CSS3 and the direct descendant selector (>).

.rubyTable > tr:nth-of-type(1n+3) > td:first-of-type {
    /* equivalent to .rubyTrack CSS properties */
}
.rubyTable > tr:nth-of-type(1n+3) > td:not(:first-of-type) {
    /* equivalent to .rubyData CSS properties */
}

The first rule targets the nth-of-type direct descendant within the .rubyTable class starting from the third occurrence. It then styles the first td element accordingly.

The second rule styles all subsequent td elements (excluding the first one) following the defined pattern. This approach eliminates the need for repetitive class assignments in your HTML markup.

By restructuring your code as demonstrated above, your HTML becomes more concise, organized, and easier to manage.

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

Tips for incorporating images as radio buttons

Can anyone assist me in setting up a straightforward enabled/disabled radio button grouping on my form? My idea is to utilize an image of a check mark for the enabled option and an X for disabled. I would like the unselected element to appear grayed out ...

Issue with drop-down menu functionality on mobile-friendly website

After deciding to revamp my website for responsiveness, I encountered an issue with the menu not displaying on smaller screens. Everything else is functioning correctly except for the drop-down menu! Here is the HTML code: <!doctype html> <html ...

How can I customize the color of Chrome's default date and time picker to a different shade of blue?

Is there a way to customize the color of the blue buttons, text, and date indicator in the native datetime picker for Chrome using CSS? https://i.stack.imgur.com/eZSaE.png ...

Preventing data loss upon submitting a form (PHP)

Currently, I have an HTML file that allows users to select appointment times for specific days of the week. Once they click submit, a PHP file generates and displays a calendar with the chosen times as checkboxes. My goal is to enable users to input their ...

Is the AngularJS Date property model sending an incorrect value to the server?

There are some puzzling things I am trying to figure out. When using datetimepicker, the Date and time selected appear correctly on the screenshot. The value in the textbox is accurate The model's value in console is correct (but hold on a second... ...

Tips for updating multiple bundled javascript files with webpack

I am working on a straightforward app that requires users to provide specific pieces of information in the following format. Kindly input your domain. User: www.google.com Please provide your vast URL. User: www.vast.xx.com Select a position: a) Bottom ...

When implementing CSS object-fit: contain on an image, it may result in empty spaces surrounding the image

Within my image-wrapper container, I have an image with a variable resolution. The container itself has fixed dimensions for height and width. My goal is to center the image within the container both horizontally and vertically while adding a box-shadow e ...

As my character slides off the moving platform in this exciting Javascript canvas game, my heart

Can anyone help me figure out how to keep my player on the moving platform? I'm not sure if I need to add gravity or something else. I'm still learning the ropes. export function checkTopCollision({ item1, item2 }) { return ( item1.y + item ...

no visible text displayed within an input-label field

Currently, I have started working on a multi-step form that is designed to be very simple and clean. However, I am facing an issue where nothing is being displayed when I click on the next arrow. I am puzzled as to why it's not even displaying the te ...

What is the correct method to sanitize the data obtained from a text area before inserting it back into the same text area?

When a user enters text into a textarea, it is directly inserted into a mySQL database. To ensure its security, I apply trim, htmlentities, mysql_real_escape_string functions to sanitize the input. Additionally, magic quotes are enabled. However, when it c ...

Is there any method to avoid the hassle of constantly adjusting margins and paddings on my one-page website?

One issue I encountered was that the buttons weren't scrolling me to the top of the anchor, instead scrolling too far into the section due to the fixed navbar overlapping. I tried solving it with margins and paddings but believe there must be a simpl ...

The markers on Google Maps are currently displaying in the wrong position, despite the latitude and longitude being correct

Utilizing the Google Maps API, I have implemented a system to dynamically add map markers tracking 2 of our company's vehicles. The website is developed in asp.net c# mvc with bootstrap 4.3.1. An ajax request retrieves the latest marker location from ...

Modify the useRef value prior to the HTML rendering (React functional component)

Hello everyone, I am attempting to update the value of useRef before the HTML is rendered. I have tried using useEffect for this purpose, but it runs after the HTML is ready, making it unsuitable for my needs. What I want to achieve is resetting the value ...

Creating a table and filling it with data from any cell is a simple process

I have a question about creating an HTML table similar to the image shown here: image I want to populate the table with data from a JSON response received from a web service: { "ErrorCode": 0, "ErrorMessage": "ok", "Data": [ { ...

Covering the entire screen, the Div element takes up the entirety of

Just like with other pages, the main div always takes up the entire screen visible to the user. As they scroll down, another div becomes visible: example1 , example2 Regardless of the screen size, the main div will always fill the space visible to the use ...

Make Fomantic-UI (Angular-JS) sidebar scroll independently

Is there a way to make a sidebar scroll independently of the content it pushes? Currently, my page is structured like this: -------------------------- |[button] Header | -------------------------- |S | Main content | |i | ...

Tips for extracting text from a multiline tag using Selenium

I need help extracting the text "1 file has been successfully uploaded" from the code snippet below: <div class="formbuttons"> <h3 id="res" class="demo" style="color: rgb(255, 255, 255); display: block;"> <center>1 file <br>has bee ...

What is the method to assign a value to ng-class in Angularjs?

I need to categorize items in a list by assigning them classes such as items-count-1, items-count-2, items-count-3, items-count-4, based on the total number of items present. This is how I would like it to appear: li(ng-repeat="area in areas", ng-class=" ...

Finding a specific cell in a Django HTML table: tips and tricks

Recently delving into django and its intricacies. Struggling to grasp the concept of accurately pinpointing a specific cell within an html table. Yearning to modify the background color of select cells based on certain conditions derived from the generate ...

Performance issues with jquery addClass and removeClass functions observed in Internet Explorer 11

I am currently working on an application that monitors nodes within a cluster, and I have created a visual state example to demonstrate this. Each small box in the grid represents a node, and when hovering over a node, the rest of the nodes in that particu ...