Yesha
Yesha

Reputation: 678

d3js: Svg element not getting resized on changing window size

I have a svg element and I am trying to make it responsive. The code that I am using is given below but this does not work. I don't understand the issue.

 var svg = d3.select('.chart')
            .append('svg')
            .attr('class', 'chart')
            .attr("width", width + margin + margin)
            .attr("height", height + margin + margin + 10   )
            .attr("viewBox", "0 0 680 490")
            .attr("preserveAspectRatio", "xMinYMin meet")
            .append("g")
            .attr("transform", "translate(" + margin + "," + margin + 
 ")");

Upvotes: 0

Views: 2017

Answers (3)

Ozan
Ozan

Reputation: 3739

That code will run only once and set its size to the initial window height and width values. If you want it to resize when window size is changed, you need to resize it on window.onresize event.

window.onresize = function() {
    // code to change svg element's width/height here
}

Upvotes: 1

Yesha
Yesha

Reputation: 678

I found the solution. Following worked for me. Thanks anyway :)

var svg = d3.select('.chart')
            .classed("svg-container", true)
            .append('svg')
            .attr('class', 'chart')
            .attr("viewBox", "0 0 680 490")
            .attr("preserveAspectRatio", "xMinYMin meet")
            .classed("svg-content-responsive", true)
            .append("g")
            .attr("transform", "translate(" + margin + "," + margin + ")");

.svg-container {
    display: inline-block;
    position: relative;
    width: 100%;
    padding-bottom: 100%; /* aspect ratio */
    vertical-align: top;
    overflow: hidden;
}
.svg-content-responsive {
    display: inline-block;
    position: absolute;
    top: 10px;
    left: 0;
}

Upvotes: 0

TKoL
TKoL

Reputation: 13912

You're setting the width and height there. From experience, I know that an SVG with width and height set is very difficult to resize. I use the viewbox only and do sizing with CSS.

Upvotes: 1

Related Questions