Search code examples
javascriptcssreactjschartsmargins

How to remove a 100% right margin from a div That holds a Chartjs canvas


I am using Chartjs to create a Chart. That Chart is being held in a ChartHold div. And even though the CSS Object has a 1px right margin the div has a 100% right margin.Because of that the other charts are under the original one but they are supposed to be next to each other

the CSS (ChartHold is the container for all the Charts and HoldChart is the div in which the chart is stored)

/* Charts */
#ChartHold{
    position: absolute;
    left: 0%;
    top: 15%;
    width: 100%;
}
#HoldChart{
    width: 300px;
    height: 200px;
    margin-right: 1% !important;
}

Even if you can't help me I hope you have an fantastical day today :)

Here are some things that I already tried:

I tried to get the DIV per ID and change its margin, I tried to change it manual with the inspect element, And I checked if it had anything to do with the Chartjs library. None of those worked. :/


Solution

  • The commenter above is correct that what you're observing in your devtools is the "empty" space that remains when there is more than the 300px of your block level element to occupy. This creates a margin on the right to take up the remaining space.

    Change your CSS and add classes to your elements (and remove the added inline styles):

    /* Charts */
    .chartHold {
     display: flex;
    }
    
    .holdChart {
      width: 300px;
      height: 200px;
    }
    

    In HTML every element id must be completely unique to the page, so you need change your markup to something like this:

    <div id="chartHold" class="chartHold">
      <div id="holdChart" class="holdChart"><div>
      <div id="holdChart2" class="holdChart"><div>
      <div id="holdChart3" class="holdChart"><div>
      ...
    </div>
    

    It is completely valid that all of your charts have the same CSS class. It's also valid that you have an id and one or more CSS classes on a single element. You might do this to make it easy to select the element by its id in JavaScript, but as a general rule, don't use ids in your CSS. It's considered an antipattern because of the added specificity ids carry.