csssvgheightviewbox

SVG content get cropped for dynamic values


I have an color legend for discrete data, which is done using SVG. But I am getting issue to display the whole content as it is getting cropped. I cannot define fixed height since content are dynamic.

FYI: My code is written in react

Note: I can give overflow: visible and make the content visible but again then the issue comes in giving background color (background color wont get apply for overflowed content).

Code link: https://jsfiddle.net/rb4p9max/4/

React.useEffect(() => {
  // calling legend function and passing div id to function
  colorLegend("#legend");
}, [dep]);

function colorLegend(legend: string) {
  // logic
  select(legend)
  .append("svg")
  .attr("height", 100 + "%")
  .attr("width", 100 + "%")
  .style("background-color", "black")
  .style("border-radius", "5px")
  .call(colorLegend);
}

return (
  <div style={{position: "absolute",right: 16,top: 10,backgroundColor: 
  "grey"}}>
    <div id="legend"></div>
  </div> 
);

Solution

  • It's hard to answer it with just a small example from the react code. But, based on the fiddle you submitted, you could set a fixed height, but based on the number of legends you have. Something like:

    height: calc(22px * 7 + (4px * 6));
    

    Explaining the numbers: 22px * 7 is because every square is 22px height. 4px * 6 is accounting for the bottom margin. You don't need a bottom margin in the last one.

    https://jsfiddle.net/gzebj1qn/

    So, the final code would be something like:

    height: calc(22px * ${legends.length} + (4px * ${legends.length -1}));