Search code examples
javascriptcssreactjsmargin

How can I prevent elements breaking to a new line because of margin?


I am trying to line all the elements in a single line. I wanted to make this dynamic so the width that I used is with percentage. What happens is that some of the elements are breaking to a new line. I understand that this is happening because of the margin and that the width does not include the margin in it's calculation. What can I do?

Here is my code:

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;

Solution

  • Have you tried using calc() CSS function for calculating width? It allows to combine px and percentage, so you can subtract your margin from the element's width.