Ensure that the headers of the table are properly aligned with the

Here's the code snippet I'm currently working with:

function deleteRow(row) {
            var i = row.parentNode.parentNode.rowIndex - 2; // this -> td -> tr // -2 because the first 2 rows are used for header
            var tbl = document.querySelector('tbody');
            if(tbl && tbl.rows.length > 1) {
                tbl.deleteRow(i); 
                Array.from(tbl.rows).forEach((row, index) => {
                        row.cells[0].innerHTML = index + 1;
                });
            }
} 

function insRow(row) {
            var i = row.parentNode.parentNode.rowIndex - 2; // this -> td -> tr // -2 because the first 2 rows are used for header
            var tbl = document.querySelector('tbody');
            var row = document.createElement('tr');
            row.innerHTML=`
                <th></th>
                <td><input size=25 type="text" id="latbox" /></td>
                <td><input size=25 type="text" id="lngbox" readonly=true/></td>
                <td><input type="button" id="delPOIbutton" value="Delete" onclick="deleteRow(this)" /></td>
                <td><input type="button" id="addmorePOIbutton" value="Add More POIs" onclick="insRow(this)" /></td>
            `;
            var len = tbl.rows.length;
            row.cells[0].innerHTML = len + 1;
            tbl.insertBefore(row, tbl.children[i+1]);
            Array.from(tbl.rows).forEach((row, index) => {
                row.cells[0].innerHTML = index + 1;
            });
            //tbl.appendChild(row);
}
html, body {
      width: max-content;
}
table {
    max-width:980px;
    table-layout:fixed;
    margin:auto;
}
th, td {
    padding:5px 10px;
    border:1px solid #000;
}
thead, tfoot {
    background:#f9f9f9;
    display:table;
    width:100%;
    width:calc(100% - 8px);
}
tbody {
    height:300px;
    overflow:auto;
    overflow-x:hidden;
    display:block;
    width:100%;
}
tbody tr {
    display:table;
    /*width:100%;*/
    table-layout:fixed;
}

th:first-of-type { width: 30px; }

th {
    background: lightblue;
    border-color: white;
  }

#latbox {width: 100px;}
    <table>
        <caption>Monthly savings</caption>
        <thead>
            <tr>
                <th colspan="5">The table header</th>
            </tr>
            <tr>
                <th>POI</td>
                <th>Latitude</td>
                <th>Longitude</td>
                <th>Delete?</td>
                <th>Add Rows?</td>
            </tr>
        </thead>
        <tbody >
            <tr>
                <th>1</th>
                <td><input size=25 type="text" id="latbox" /></td>
                <td><input size=25 type="text" id="lngbox" readonly=true/></td>
                <td><input type="button" id="delPOIbutton" value="Delete" onclick="deleteRow(this)" /></td>
                <td><input type="button" id="addmorePOIbutton" value="Add More POIs" onclick="insRow(this)" /></td>
            </tr>
        </tbody>
        <tfoot>
            <tr>
                <th colspan="5">The table footer</th>
            </tr>
        </tfoot>
    </table>

The alignment of the header cells' titles doesn't match with the body cells. How can I adjust this using CSS?

Answer №1

Consider reducing the amount of CSS styling

function removeRow(row) {
            var index = row.parentNode.parentNode.rowIndex - 2; // this -> td -> tr // -2 because the first 2 rows are used for header
            var tableBody = document.querySelector('tbody');
            if(tableBody && tableBody.rows.length > 1) {
                tableBody.deleteRow(index); 
                Array.from(tableBody.rows).forEach((row, idx) => {
                        row.cells[0].innerHTML = idx + 1;
                });
            }
} 

function insertRow(row) {
            var index = row.parentNode.parentNode.rowIndex - 2; // this -> td -> tr // -2 because the first 2 rows are used for header
            var tableBody = document.querySelector('tbody');
            var newRow = document.createElement('tr');
            newRow.innerHTML=`
                <th></th>
                <td><input size=25 type="text" id="latbox" /></td>
                <td><input size=25 type="text" id="lngbox" readonly=true/></td>
                <td><input type="button" id="delPOIbutton" value="Delete" onclick="removeRow(this)" /></td>
                <td><input type="button" id="addmorePOIbutton" value="Add More POIs" onclick="insertRow(this)" /></td>
            `;
            var length = tableBody.rows.length;
            newRow.cells[0].innerHTML = length + 1;
            tableBody.insertBefore(newRow, tableBody.children[index+1]);
            Array.from(tableBody.rows).forEach((row, idx) => {
                row.cells[0].innerHTML = idx + 1;
            });
}
html, body {
      width: max-content;
}
table {
    max-width:980px;
    table-layout:fixed;
    margin:auto;
}
th, td {
    padding:5px 10px;
    border:1px solid #000;
}
th {
    background: lightblue;
    border-color: white;
  }

#latbox {width: 100px;}
  <table>
        <caption>Monthly savings</caption>
        <thead>
            <tr>
                <th colspan="5">The table header</th>
            </tr>
            <tr>
                <th>POI</td>
                <th>Latitude</td>
                <th>Longitude</td>
                <th>Delete?</td>
                <th>Add Rows?</td>
            </tr>
        </thead>
        <tbody >
            <tr>
                <th>1</th>
                <td><input size=25 type="text" id="latbox" /></td>
                <td><input size=25 type="text" id="lngbox" readonly=true/></td>
                <td><input type="button" id="delPOIbutton" value="Delete" onclick="removeRow(this)" /></td>
                <td><input type="button" id="addmorePOIbutton" value="Add More POIs" onclick="insertRow(this)" /></td>
            </tr>
        </tbody>
        <tfoot>
            <tr>
                <th colspan="5">The table footer</th>
            </tr>
        </tfoot>
    </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

Tips for refreshing extensive JSON structures?

I receive product data from the server in JSON format, containing properties and nested arrays up to 4 levels deep. In the frontend, users can update values within these nested structures. Should I keep track of the path and reconstruct the entire JSON obj ...

The previous user's selection of checkboxes will be disabled

https://i.stack.imgur.com/fH1g2.pnghttps://i.stack.imgur.com/Oiu6q.pngI am facing an issue where I want all the records (seats selected by the user) to be disabled, but the code provided only fetches the last record and disables it. <?php ...

Pull information from database based on selection made in combo box

I am attempting to populate a text box with values from a database based on the selection in a combo box. I have written the code below but it doesn't seem to be working correctly. The issue is that the value selected in the combo box is not being pas ...

Error thrown due to syntax issues in react.d.ts declaration file in TypeScript

Currently, I am attempting to integrate react with typescript in my project. However, typescript is generating syntax errors for the react.d.ts file sourced from Github: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/react The encountered ...

Can we leverage Angular service styles in scss?

I am working on a change-color.service.ts file that contains the following code snippet: public defaultStyles = { firstDesignBackgroundColor: '#a31329', firstDesignFontColor: '#ffffff', secondDesignBackgroundColor: '#d1 ...

A button featuring an extensive label that utilizes text-overflow ellipsis is initially set with a max-width of 700px. However, it should dynamically shrink when the viewport size decreases

My Request I need a button that can accommodate both long and short labels, with the text getting cut off at 700px using ellipses. The button should adjust to the available space when the viewport is smaller than 700px. The length of the label can vary gr ...

Issue with React-Native FlatList's scrolling functionality

Struggling with implementing a scrolling FlatList in React Native. Despite trying various solutions found on Stack Overflow, such as adjusting flex properties and wrapping elements in views, the list still refuses to scroll. Snippet of code (issue is with ...

To close the menu, simply tap on anywhere on the screen

Is there a way to modify a script so that it closes the menu when clicking on any part of the screen, not just on an 'li' element? $(function() { $('.drop-down-input').click(function() { $('.drop-down-input.selected').rem ...

What is the process for connecting an event to the <body> element in backbone.js?

Could it be done? For example, like this: ... interactions { 'click button' : 'performAction' } ... ...

Converting CSV data into JSON format using NodeJs and integrating it with MongoDB

Here is how my CSV file is structured: "Some Comment here" <Blank Cell> Header1 Header2 Header3 Value1 Value2 Header4 Value3 Value4 I am looking to convert this into JSON format and store it in MongoDB as follows: Obj: { Key1: Header ...

Display JSON data using Vue.js

Trying to display JSON file results using Vue.js, with the goal of showing the result in a value. Here is the code snippet: data () { return { fetchData: function () { var self = this; self.$http.get("/api/casetotalactivation", functio ...

Trouble accessing selected value from drop down list in ASP.NET codebehind following modification of Javascript attribute

Does anyone know why ASP.NET code behind cannot retrieve the selected value? After investigating, I discovered that the issue lies within the JavaScript function; Specifically in the set attribute section: process.options[process.selectedIndex].setAttrib ...

Can Vue.js automatically refresh the display when there are changes in a third-party JSON file?

I'm attempting to achieve a specific goal using Vue, but I'm uncertain if it's feasible given my current struggles in obtaining the desired outcome: An API endpoint returns an array containing multiple objects. While I am able to successfu ...

What could be the reason behind the button's lack of color change with this particular code?

I'm a beginner in web development and currently practicing HTML, CSS, and Javascript. I've added a button to my html file and would like the color of the button to change when it's clicked on. Here is my HTML code: <button id="box&q ...

Executing an HTTP POST request without properly encoding a specific parameter

I am attempting to communicate with an unauthorized third-party API using Node and the request module. Below is the code that generates the request: request.post( { url: url, headers: MY_HEADERS_HERE, followAllR ...

importing with a specific name may result in errors, while importing everything with * from does not

Exploring the directory layout of features within my react application: feature1 actions actionTypes.js crud.js component.js container.js reducer.js sagas.js sagas.test.js services.js index.js feature2 ...

How can I align a single button to the left side while positioning the rest of the elements to the right in Bootstrap 4?

I am attempting to align the B1 button on the left side and have the remaining elements positioned on the right side. Below is my code snippet using Bootstrap 4.1: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/b ...

Is it possible for me to invoke an anonymous self-executing function from a separate scope?

I'm having an issue with calling the hello() function in ReactJS. When I try to call it, I receive an error message that says "Uncaught ReferenceError: hello is not defined". How can I go about resolving this error? This is a snippet from my index.ht ...

What is the method to create all possible combinations from the keys of a JSON object?

How can I generate object B that includes all combinations of object A using a key-value pair? { "x": "data-x", "y": "data-y", "z": "data-z" } The desired output should look like this: { ...

Challenge with timing in slideUp and slideDown animations (jQuery)

The element with the class "heady" is designed to slide up when the document height percentage is below 25%. If you scroll back up, it should reappear after a delay of 1400ms. The problem arises when this action needs to repeat, as the class does not sli ...