What measures can I take to avoid elements wrapping to the next line due to margins?

Is there a way to align all elements in a single line when using dynamic percentage widths? I noticed that some of the elements are wrapping to a new line, likely due to margins not being included in the width calculation. Any suggestions on how to fix this?

Below is my code snippet:

import React, { useState, useEffect } from 'react';

const randomIntFromInterval = (min, max) => {
    return Math.floor(Math.random() * (max - min + 1) + min);
}

const Dummy2 = () => {
    const [arr, setArr] = useState([]);
    const [length, setLength] = useState(10);

    useEffect(() => {
        generateArray();
    }, [length]);

    const generateArray = () => {
        const temp = [];
        for(let i = 0; i < length; i++) {
            temp.push(randomIntFromInterval(7, 107));
        }
        setArr(temp);
    }

    const handleLength = (e) => {
        setLength(e.target.value);
    }

    const maxVal = Math.max(...arr);

    return (
        <div>
            <div className="array-container" style={{height: '50%'}}>
                {arr.map((value, idx) => (
                    <div className="array-element"
                         key={idx}
                         style={{height: `${(value * 100 / maxVal).toFixed()}%`,
                                 width: `${100 / length}%`,
                                 margin: '0 1px',
                                 display: 'inline-block',
                                 backgroundColor: 'black'}}
                    ></div>))
                }
            </div>
            <div>
                <button onClick={() => generateArray()}>New array</button>
            </div>
            <div className="slider-container">
                1
                <input type="range" 
                       min="1" 
                       max="100" 
                       onChange={(e) => handleLength(e)} 
                       className="slider" 
                       id="myRange" 
                />
                100
            </div>
            {length}
        </div>
    );
}

export default Dummy2;

Answer №1

If you haven't experimented with the calc() CSS function yet, it's definitely worth a try. This powerful tool enables you to calculate widths by combining pixels and percentages. By utilizing this function, you can easily subtract margins from an element's width for more precise control over your layout.

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 most effective way to prevent a <pre> element from overflowing and instead horizontally scrolling when placed within a table cell that is not

I am faced with the following situation: <table> <tbody> <tr> <td> <pre style="overflow: scroll;"> (very long lines of text) Find my JSFiddle here: https://jsfiddle ...

Employing the powerful Math.pow() function within the setState() method

In this ReactJS code example, the goal is to update the value of a div element with every click of a button using the Math.pow() method. However, it seems that the method is not working as intended. Can someone explain why? The handlerButton function in ...

What is the best way to integrate tailwind (tw.macro) when passing a function as a prop in next.js?

Sidebar.tsx import React from 'react'; import { Props } from './SidebarRow.i'; import tw from 'twin.macro'; function SidebarRow({ Icon, title }: Props) { return ( <div> <Icon tw={'h-6 w-6'} /> ...

Modifying CSS in JQuery does not seem to have a lasting effect

My webpage uses JQuery to dynamically hide and show different parts of the content when a button is clicked. However, I am facing an issue where the changes only last for a brief moment before reverting back to the default styling... Here is a snippet of ...

Is there a way to implement a @click event on a Vuetify expansion panel?

Whenever I use <a>, the design of the <v-btn> expansion panel breaks. How can I incorporate the click event in this situation? I attempted to utilize filters, watch, and computed, but it didn't work. Here's my code: <v-card xs1 ...

What are the differences between three.js domElement and the documentElement?

When referring to the THREE JS documentation, it suggests using domElement in this manner: document.body.appendChild(renderer.domElement); I'm wondering if there is a distinction between this approach and utilizing documentElement instead. This is c ...

react-oidc-context automatically redirects to the original route upon successful login using Auth0

Greetings! I am currently attempting to implement authentication using react-oidc-context with auth0, but I have encountered an issue. Upon successful authentication with auth0, I always get redirected back to the route I was on when I clicked the login bu ...

Utilizing AJAX to fetch and retrieve a JSON array

Check out the javascript code below: var formSerializedData = $('form#registration-form').serialize(); $.post( '<?php echo $this->url('/register', 'do_register')?>', function(response) { alert(response); } ...

showing the chosen item in a Bootstrap dropdown [limited to the first menu option and using the attr() method]

Is there a way to dynamically display the selected menu option using the bootstrap drop down? Initially, I was able to select the first menu option and apply it to the bootstrap drop-down button. However, I encountered an issue where I cannot change the ...

Backgrounds filled by nested <li> elements inside another <li> element

My website features a sidebar menu with nested lists. When hovering over a list item, a sub-list appears. However, I am having an issue where the background color fills the entire sub-list instead of just the first list item. See the images below for clari ...

Issue with Angular UI Router arises when state cannot be resolved upon page reload

I'm currently facing an issue with routing that I mentioned in the title. Even though my route is functioning, it encounters difficulties when the page is reloaded. Below is the routes object: { state: 'locations', config: { ...

Steps for mandating the specification of a type parameter for a generic React component

When setting up a new instance of a generic React component, I noticed that the TypeScript type checker automatically defaults to unknown without requiring me to specify the type argument: https://i.sstatic.net/1hT6H.png Ideally, I would prefer if TypeSc ...

Having trouble getting Firestore/Firebase to work with Next.js?

Hey everyone, I could really use some help here. I've been working on integrating Firebase into my Next.js app for the API. Everything works well when I build and run locally, but once I deploy to Vercel for production, I encounter a 500 - Internal S ...

How to display error messages in React Formik for invalid email and password entries

I need a form that displays an error message like "email/password incorrect" when wrong credentials are entered, currently nothing is displayed. Here is the code I have: `const loginSchema = yup.object().shape({ email: yup.string().email("invalid email") ...

Decode array in JavaScript

Hello, I'm currently trying to deserialize this array in JavaScript using the PHPunserialize module: a:7:{s:13:"varPertinence";a:4:{i:0;s:5:"REGLT";i:1;s:2:"13";i:2;s:2:"15";i:3;s:2:"16";}s:10:"varSegment";N;s:12:"varSSegment1";N;s:12:"varSSegment2"; ...

Dynamic Content in jQuery UI Tooltip

Is it possible to dynamically change the tooltip content as I drag the div that contains the tooltip? I want to display the ui.position.top in the tooltip during the drag event. I have checked the jQuery UI API documentation for tooltip content, which ment ...

Unexpected behavior in Firefox occurs with PreloadJS when trying to preload elements that are added to the page after the initial load

I'm encountering an issue with the behavior of PreloadJS specifically on Firefox. It's surprising to me that no one else seems to have experienced this problem before as I couldn't find any similar descriptions online. Perhaps I am simply ov ...

Take action upon being added to a collection or being observed

Consider the following scenario: I have an array called "x" and an Observable created from this array (arrObs). There is a button on the page, and when a user clicks on it, a random number is added to the array. The goal is to display the newly added value ...

Uncovering the Secrets of Retrieving Nested Objects with MongoDB and Mongoose

I have a collection of documents stored in my mongodb database, each structured like this: { "current" : { "aksd" : "5555", "BullevardBoh" : "123" }, "history" : { "1" : { "deleted" : false, ...

Finding the Client's Private IP Address in React or Node.js: A Comprehensive Guide

Issue I am currently facing the challenge of comparing the user's private IP with the certificate's IP. Is there a method available to retrieve the user's private IP in react or node? Attempted Solution After attempting to find the user&a ...