Ensure that the width of the div element corresponds to the width of its contents

My challenge is to center a react handsontable component within a container div while maintaining its autosizing feature. In this scenario, I aim for the width of div #example1 to adapt based on the table's content (adjusting as the number of columns changes).

For reference, here is the example: https://jsfiddle.net/opike99/b1ux0rLy/5/

HTML:

<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9df5fcf3f9eef2f3e9fcfff1f8ddacacb3ac">[email protected]</a>/dist/handsontable.full.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1b9b0bfb5a2bebfa5b0b3bdb491e0e0ffe0">[email protected]</a>/dist/handsontable.full.min.css" /> 
<script src="https://handsontable.com/docs/8.3.2/components/numbro/dist/languages.min.js"></script>

<div class="outer2">
<div class="outer1">
  <div id="example1">



  </div>
</div>
</div>

JS:

const container = document.querySelector('#example1');

const numberOfColumns = 7;

const hot = new Handsontable(container, {
  data: Handsontable.helper.createSpreadsheetData(5, numberOfColumns),
  colHeaders: true,
  rowHeaders: true,
  hiddenColumns: true,
  width: 'auto',
  height: 'auto',
  licenseKey: 'non-commercial-and-evaluation',
});


// re-render your Handsontable instance
hot.render()

CSS:

.outer2 {
}

.outer1 {
}

#example1 {
    border-style: solid;
    /* width: fit-content; */
}

Answer №1

I have been experimenting with the sample you provided and came up with some interesting findings:

There are actually three key steps to follow:

  1. The $('.wtHolder') element is set with a width: 680px in its style attribute, so it can only be removed programmatically.
  2. $('.ht_master.handsontable, #example1')
    should have width: fit-content
  3. By using flexbox, I managed to center the table by applying
    display: flex; justify-content: center;
    to $('.outer1').

It's worth noting that the order of application for these steps matters. To achieve this, I used a setTimeout, but you may need a more refined approach.

setTimeout(function() {
    document.querySelector('.wtHolder').style.width = 'initial';
  document.querySelector('#example1').style.width = 'fit-content';
  const outer = document.querySelector('.outer1');
  outer.style.display = 'flex';
  outer.style.justifyContent = 'center';
}, 2000);

Feel free to share your progress with me.

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

What is the proper way to include an authorization token in the header when using Axios.post in a

Discussing my project involving React, Express, and MongoDB. I am encountering a 403 error (Forbidden) when trying to pass the authentication token via header for Axios post request. Data Retrieval In this section, I am fetching and retrieving all authe ...

Is Angular 4 having trouble with certain video file extensions for video previews?

I'm currently facing an issue with video previews. I am able to display mp4 file extensions for the preview, but other file extensions like mpeg, m4v, wmv, etc. are not working with the current code. Even though I added all file types in the video sr ...

What is the best way to enhance accuracy when hovering?

Have you ever noticed that the bottom menu becomes less precise when hovering over it on certain browsers? While Firefox seems to handle it perfectly, other browsers lack that smooth "snap" effect as you move through the numbers. I'm trying to find a ...

Testing the axios mock with a 400 response does not result in the expected value being returned

Currently, I am utilizing nock to simulate my ajax call with axios. Below is the code snippet that I am working with: describe("unSuccessful rest call",()=>{ it('should dispatch types: SET_DROP_DOWN_CHECK_STATUS in order ', () => ...

Creating a filter using radio input in HTML and CSS is a simple and

Currently, I am delving into the world of Javascript and React, but I have hit a roadblock. My goal is to create a Pokedex, yet I am encountering some difficulties. I have implemented Radio Inputs to filter Pokemon by generation, but I am struggling with ...

What causes my animation to “reset” upon adding a new element using innerHTML?

One of the functionalities on my webpage involves a script that inserts a div called "doge" using innerHTML when a button is clicked. Additionally, there is a CSS keyframes animation applied to another div on the same page. However, whenever the button is ...

Using jQuery to perform global search and replace with a variable

In this scenario, I am attempting to substitute every occurrence of the newname variable with a hyphen (-). However, in my specific case, newname is being interpreted as text instead of a variable. var newname = 'test'; var lastname = $(this).a ...

When hovering or mousing over, the text remains stationary and does not follow the scroll bar movement within the

A method I am using involves displaying additional data on hover for a shortened header, like this: Hover behavior However, the text shifts across the page when the scrollbar is used, as shown here: Scrollbar interaction This table showcases HTML, CSS, ...

"Issue with jQuery click event on anchor tag not functioning properly with

I have encountered this code which I've adapted slightly from a book (novice to ninja). When the user clicks on 'contact', a form opens underneath with a phone number and href link. Interestingly, left-clicking on the link does nothing, but ...

Navigate through inner divs on iOS using VoiceOver by performing a 3-finger swipe up or down

I'm currently experimenting with VoiceOver and scrolling, specifically the three-finger swipe up/down gesture on my test page located at: http://107.170.41.208/AccessibleHTML The test page consists of a div with scrollable content (red background) f ...

Utilizing JQuery to extract data from a <select> dropdown menu

Is there a way to retrieve the current value of a SELECT tag using JavaScript or jQuery? I have tried using $('select').val(), but it only returns the default value and does not update when changed. Any suggestions on how to solve this issue? $( ...

Using Lightmaps with Three.js

Is it true that lightmaps function independently of other textures? It seems like I need to establish a second set of UVs. I've exported my JSON object with a second set of UVs and included the following code snippet: geometry.faceVertexUvs[0] = ge ...

Animating object properties instead of static values

I am faced with a challenge of dealing with a large array of objects, all having the same structure: { title: 'Text', value: 'Text'} My goal is to loop through this array using a map function and display only two objects at a time. Th ...

Issues with Dreamweaver CS5's live preview feature and compatibility with different web browsers

Hey there, I recently sliced an image using Fireworks and exported it to HTML. After opening the HTML file in Dreamweaver, I saved it as PHP and everything seemed fine. Then, I replaced some images with HTML input tags and buttons, setting their width and ...

Removing a row from a table using a button click in PHP

I am experiencing difficulty passing the ID of the button to delete the corresponding row. What steps should I take to ensure that the ID is passed correctly? <form method="POST" > <table border="1"> &l ...

I am getting NaN as the output from my function, but I am unsure of the reason behind

For pracitce, I have created this code to calculate the total amount spent on gas and food using arrays. However, I am encountering an issue where it is returning NaN. const gas = [20, 40, 100]; const food = [10, 40, 50]; function total(gas, food) { ...

Showing specific XML data from a node when a button is clicked in an HTML document

<script> $(document).ready(function(){ $.ajax({ type: "GET", url: "data.xml", dataType: "xml", success: function(xmlData) { $("POS", xmlData).each(function(){ var sr = $(this).find(&apos ...

Is the epoch date format not compatible with the ngx bootstrap datepicker?

Consider this scenario: Jun 13, 2003, 23:11:52.454 UTC represented in epoch date format as 1055545912454. However, when I input this value as bsValue, I receive undefined. Objective My goal is to send the date in epoch format when making a server request ...

Is it possible for me to create a distinct component that can display numerous input fields at once?

Introducing the inputArea component, which collects data from input fields and sends it to the server: export default class InputArea extends React.Component { constructor(props){ super(props); this.state = { draw_number: '', ...

Determine if every object in the array contains a specific key value pair

I am dealing with the following JSON data: { records:{ data:{ current:{ records:{ '2years':[{a:1, b:2, flag:true}, {a:2, b:4}, ...