Precise column measurement

I'm currently working on a jQuery project where I need to create a table with columns of exact widths.

For example, let's say I want the first column to be exactly 100px wide, including padding (10px on each side). I've tried various combinations of width() and innerWidth() functions, but encountered some unexpected results in my attempts:

  1. I created a td element and set its width using td1.width(100);. However, when I checked the values using td1.width() and td1.innerWidth(), they returned 120px and 140px respectively. The actual column width shown in the Firefox console was 140px.

  2. On another attempt, I used td1.innerWidth(100); instead. This time, the functions returned 100px for td1.width() and 120px for td1.innerWidth(). Again, the column width reported by Firefox was 120px.

I am puzzled as to why td1.width(100); behaves in this strange manner?

But the real question remains: is there any way to achieve a column with an actual width of 100px, properly including padding?

.js file

var bodyTable = $("<table>");
var body = $("<tbody>");
var tr1 = $("<tr>");
var tr2 = $("<tr>");

$("#testTable").append(bodyTable);
bodyTable.append(body);
body.append(tr1);
body.append(tr2);

var td1 = $("<td>foo</td>");
var td2 = $("<td>foo</td>");
var td3 = $("<td>foo</td>");
var td4 = $("<td>foo</td>");
var td5 = $("<td>foo</td>");
var td6 = $("<td>foo</td>");
tr1.append(td1);
tr1.append(td2);
tr1.append(td3);
tr2.append(td4);
tr2.append(td5);
tr2.append(td6);

td1.width(100);
console.log(td1.width(), td1.innerWidth());    //Result: 120 140

td1.innerWidth(100);
console.log(td1.width(), td1.innerWidth());    //Result: 100 120

.css file

#testTable td {
  padding:10px;
}

.html file

<div id="testTable"></div>

Answer №1

Don't be misled by the name "inner width", as it actually refers to the total width of an element including padding. For example, if you have a 100px wide element with 10px padding all around, the innerwidth would be 120px (100+10left+10right).

This image serves as a comprehensive guide explaining the concepts of widths, innerwidths, and more.

https://i.stack.imgur.com/s6Bqd.gif

NOW, in my example below, I've created a red box with a 100px width and placed a blue box inside it with 10px padding. Despite the padding, the blue box remains 100px wide because the red box expands to 120px. It's noteworthy that the blue box itself has no padding, so both its innerWidth and width will be 100px.

$( document ).ready(function() {
    $(".reddims").append("<p>inner width: " + $(".red").innerWidth() + "</p>");
    $(".reddims").append("<p>width: " + $(".red").width() + "</p>");
    $(".bluedims").append("<p>inner width: " + $(".blue").innerWidth() + "</p>");
    $(".bluedims").append("<p>width: " + $(".blue").width() + "</p>");
    $(".bluedims").append("<p>Because Blue doesn't have paddings.</p>");
});
.red {
width: 100px;
height: 100px;
padding: 10px;
background-color: red;
}
.blue{
background-color: blue;
width: 100%;
height: 100%
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="red">
<div class="blue">
</div>
</div>
<div class="reddims">
<p>Red Dimensions are: </p>
</div>
<div class="bluedims">
<p>Blue Dimensions are: <p>
</div>

BUT AT THE END, for your specific case, consider this alternative approach which allows greater flexibility in design customization.

var td1 = $("<td class='td1'>foo</td>");
var td2 = $("<td class='td2'>foo</td>");
var td3 = $("<td class='td3'>foo</td>");
var td4 = $("<td class='td4'>foo</td>");
var td5 = $("<td class='td5'>foo</td>");
var td6 = $("<td class='td6'>foo</td>");

I trust this clarifies any queries you may have.

PICTURE CREDIT : https://www.w3schools.com/jquery/jquery_dimensions.asp

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

Linking all styles with Angular 2

Is it possible to apply a style when the exact nature of that style is unknown? Consider a scenario where I have a model containing string variables defining styles, as shown below: myStyle1:string="margin-left:10px"; myStyle2:string="margin ...

Including a link in PHP results in the creation of a new cookie each time the include statement is executed

Issue: I am facing a problem while trying to retrieve JSON data after logging in with a previous login link. Before I can access the JSON data, I need to log in using the following link: '...server.net/System?action=login&user=ro&password=12& ...

Personalized jQuery Slider, Go back to initial slide

Working on enhancing my jQuery skills by constructing a basic slider with 3 slides. The slider wrapper, with a fixed width of 1400px and a height of 350px serves as the outer container. Within this wrapper lies an unordered list where its items are floate ...

Catching exceptions with jQuery Ajax

I'm facing a tricky issue with an exception that seems to slip through my fingers: //myScript.js.coffee try $.ajax async: false type: "GET" url: index_url success: -> //Do something error: -> //Do something els ...

Is there a way to locate ComputedStyle elements using Nokogiri?

I am currently using Ruby along with Nokogiri to parse through HTML documents. I am looking to select all nodes that match a CSS class with the style attribute display: none, but the CSS class is unknown in advance. For example: <html> <body&g ...

JQuery Chosen extension - Go back to "Choose an option"

This is a select element with the Chosen plugin applied to it: <label class="radio-inline"><input type="radio" name="reset" value="reset">Reset</label> <select id="listclient"> <option value=""></option> <option val ...

What is the method for accessing a JQuery mapping array in PHP?

I am attempting to transfer data from JQuery to PHP and then save it in the database. Here is my JQuery code snippet: var map = $.map(customFieldIds, function(value) { return { name: value, value: customFieldValues[value] ...

JavaScript runtime error: Unforeseen exception code 0x800a138f has occurred

Encountering an exception when attempting to add a rule to a Radiobutton List using the rules() method. Error found at line 3747, column 3 in 0x800a138f - JavaScript runtime error: Unable to get property 'jQuery223064526755237397352' of undefin ...

Creating diagonal background cutouts using CSS

Can you create a diagonal cut in a background color using CSS? Check out this example .item { color: #fff; font-size: 30px; background-color: #565453; padding: 10px 10px 10px 10px; width: 52%; text-align: center; display: inline-block; } ...

Why is the defaultDate property not functioning properly in Material-UI's <DatePicker/> component with ReactJS?

I recently implemented the <DatePicker/> component from Material-UI ( http://www.material-ui.com/#/components/date-picker ) in my project. I encountered an issue while trying to set the defaultDate property to the current date on my computer, as it r ...

Hovering over a link causes malfunction in CSS drop-down menu

I have been struggling for hours to make this drop-down menu work, but it just won't cooperate. I want the list menu .dropdown to appear when you hover over .droptoggle. I'm including the entire page because I can't figure out what's wr ...

What causes this statement to consistently be incorrect?

I am in the process of developing a Q&A platform where users can vote on answers. I have assigned project.problem.upVoted to store a list of answers that the user has already upvoted. If an answer has already been voted on, the callback function for cl ...

Error: Unable to modify the div content - Uncaught TypeError: Unable to assign value to innerHTML of null

Attempting to update the contents of a div using JavaScript and innerHTML, but encountering an issue. After implementing the code to change the div's content, the functionality stopped working. The syntax has been double-checked. Tools being used in ...

Trigger a JQuery popup by toggling a class with a button

Hey there! I have a modal popup that utilizes an active class. When this class is present, the modal appears, and when it is removed, the modal disappears. I am trying to create a button that, when pressed, will show the modal, and a close button inside th ...

Which is the better choice: jQuery or AJAX?

After careful consideration, I have chosen to utilize jQuery for all of my client-side AJAX requirements. However, I find that there are numerous functions in jQuery that can accomplish the same task, such as $.post, $.get, $.ajax, and $.getJSON. What woul ...

Troubleshooting Problems with Ajax File Uploads

Welcome to My Unique HTML Form <center> <form enctype="multipart/form-data"> {{ csrf_field() }} <label class="fileContainer"> <input type="file" id="uploadFile" name="input_upload_file[]" multiple /&g ...

Utilize JQuery's .load() function to transmit JSON data to your Flask server

I am attempting to utilize JQuery's .load() function in order to transmit data to my Flask server and then, with that information, display a <div> that is loaded into the element making the request. This is what my code snippet looks like: $(&qu ...

Is it possible to utilize jQuery Validate to validate Heapbox elements?

I am currently working on developing a form that utilizes the heapBox library as a replacement for traditional <select> elements, along with jQuery Validate for validating the form input. The issue I'm facing is that jQuery Validate requires fo ...

Disappearance of CSS borders when using jQuery scroll function

After implementing a fixed table header for an HTML table on my website, I encountered a minor issue. When scrolling down, the table header remains at the top as intended, but the CSS styling for borders within each <th> element disappears. The font ...

Creating a table with both a fixed header and a fixed column using only CSS

I'm looking to create an HTML table with a fixed header and fixed first column, but I want to avoid using JavaScript or jQuery to set scrollTop/scrollLeft for smooth functionality on mobile browsers. I found a solution that fixes the first column he ...