how to make svg responsive

前端 未结 2 697

I\'m trying to make this massive svg responsive. However, it\'s not working and I don\'t know why.

I tried the following: - setting width: 100% height: auto (the dia

相关标签:
2条回答
  • 2020-12-10 23:14

    I was unable to find anything native to SVG that could help you (I tried messing around with viewBox and preserveAspectRatio, but didn't have much success). I am sure there must be a way but I might be over looking something. If anyone has a better solution by all means post it!

    I did get a JavaScript approach working so I thought I'd share it. In this demo I will use jQuery, but all of this could be done with vanilla JavaScript if you cannot use jQuery.

    JavaScript:

    $(function(){
        scaleSVG();
    });
    
    function scaleSVG(){
        var window_width = $(window).width(),
            $svg = $('svg'),
            ratio = window_width / $svg.width();
    
        $svg.css('min-width', window_width);
        $('g:first-child', $svg).attr('transform', 'scale(' + ratio + ')');
    };
    

    I have made a fiddle demoing this approach here (it may take a second to load because of the size of the SVG).

    You could probably also attached this scaleSVG() function to the window resize event like this:

    $(function(){
        $(window).on('resize', scaleSVG);
    }); 
    

    I wasn't able to get this to work in the fiddle, but I'm thinking its because of the fiddle environment maybe???

    0 讨论(0)
  • 2020-12-10 23:23

    Contrary to the assumptions in the comments it is perfectly fine to use length values specified as percentages. The spec covers the details in its basic data types section.

    Combining this knowledge with the hints from the article you linked to in your question you could end up with something like the following for a responsive layout:

    <svg viewbox="0 0 3840 7000" width="100%" height="100%" preserveAspectRatio="xMinYMin meet">
    
    0 讨论(0)
提交回复
热议问题