Don Smythe
Don Smythe

Reputation: 9804

Scale SVG background to fill screen without white borders preserving aspect ratio

I am using a SVG background image, with a SVG and HTML layer above. I have the SVG scaling ok on screen resize but sometimes white areas appear on sides of the image - eg short height wide width.

Is there a way to scale the image, preserving aspect ratio, and forcing the image to fit either width or height depending on which is bigger then the current width/height. Eg where screen height is short and width is wide one would not see bottom of image but the image would fill the entire width.

Preferably using CSS, vanilla JS is OK too.

Current html:

<html><body>
    <div class="container">
        <img class="svg_container" src="image.svg" id="svg_bg">
        <svg class="svg_container" id="svg_area"></svg>
        <div id='html_overlay'>
            <div id="heading_area">
                <h3>Some text</h3>
            </div></div></div></body></html>

the css:

.svg_container {
    position:fixed;
    top:0;
    left:0;
    width:100%;
    height:100%;
    overflow:hidden
}
#svg_bg {
    overflow:hidden;
    z-index: -1;
}
#svg_area {
    z-index: 1;
}
#html_overlay{
    position:fixed;
    top:0;
    left:0;
    width:100%;
    height:100%;
    z-index: 100;
}
body {
    font-family: sans-serif;
}

Upvotes: 2

Views: 4882

Answers (1)

Dave F
Dave F

Reputation: 1985

I believe that this might be what you're looking for:

body {
    background: url(test.svg) no-repeat;
    background-size: 100vw auto;
}

@media (orientation: portrait) {
    body {
        background-size: auto 100vh;
    }
}

By default, the image width will fill 100% of the view port width (100vw), but if the page has a height that is greater than the width (or has a landscape orientation) the background-size is overridden so that the image height fills 100% of the view port height (100vh).

Upvotes: 3

Related Questions