Home > Mobile >  Make svg color scale fit the size of the parent div
Make svg color scale fit the size of the parent div

Time:03-23

I have been using SVG to create the Discrete legend color selector. I want the color selector div to have fixed width and the content (svg cells) should fit based on the width of the div. Note that since the code is long, i am just pasting few lines of code.

var cellWidth = 22;
var cellHeight = 22;

// this is not the full code

const selectedLegend = select(divRef.current);
selectedLegend
.append("div")
.append("svg")
.style("margin-top", "13px")
.style("margin-left", "137px")
.style("margin-right", "35px")
.style("width", "100%")
.style("height", "25px")
.style("background", "red")

// Code to fill the color

g.selectAll("g.legendCells")
.append("rect")
.attr("height", cellHeight)
.attr("width", cellWidth)
.style("fill", function (d: Record<string, unknown>) {
return d["color"];

// Alighment of cell in straight line

g.selectAll("g.legendCells")
.attr("transform", function(d: any, i: number) {
return "translate("   (i * cellWidth)   ",0)" })

enter image description here

I want legend to take full width, it must cover whole background red color.

To be more precise, I want something like as shown below, the rect cells must fit the constant width.

enter image description here

CodePudding user response:

If you are not setting a width on the svg and use the viewBox attribute the SVG will just fill the entire space.

Update

The image should stretch: At all times the width should be 100% and the height should be fixed (here 50px). To make the image stretch you set the preserveAspectRatio attribute to "none".

#container svg {
  display: block;
}
<div id="container">
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 2"
  width="100%" height="50" preserveAspectRatio="none">
    <rect width="20" height="2" fill="#eee"/>
    <rect x="0" y="0" width="1" height="1" fill="#000"/>
    <rect x="1" y="0" width="1" height="1" fill="#111"/>
    <rect x="2" y="0" width="1" height="1" fill="#222"/>
    <rect x="3" y="0" width="1" height="1" fill="#333"/>
    <rect x="4" y="0" width="1" height="1" fill="#444"/>
    <rect x="5" y="0" width="1" height="1" fill="#555"/>
    <rect x="6" y="0" width="1" height="1" fill="#666"/>
    <rect x="7" y="0" width="1" height="1" fill="#777"/>
    <rect x="8" y="0" width="1" height="1" fill="#888"/>
    <rect x="9" y="0" width="1" height="1" fill="#999"/>
    <rect x="10" y="0" width="1" height="1" fill="#aaa"/>
  </svg>
</div>

  • Related