SVG with complete coverage of width and height

Here's the challenge: create a full window svg image with aspect distortion without using an SVG tag. Why avoid the SVG tag? Because I plan to replace the SVG later on (possibly frequently) and haven't found a simple way to do so.

Previous attempts:

  <!-- My styles are in a css file, but for demonstration purposes, 
       they are inline style attributes -->

  <!-- Works in Webkit but not in Firefox; Firefox blocks stretching 
       and centers the svg within the tag -->
  <img src="my.svg" style="width:100%;height:100%;
       position:fixed;top:0;left:0;bottom:0;right:0;" />

  <!-- Both Webkit and Firefox prevent distortion, causing the svg 
       to be centered in the div instead of conforming to its dimensions -->
  <div style="width:100%;height:100%;position:fixed;top:0;
       left:0;bottom:0;right:0;background-size:cover;
       background-image:url(my.svg);" />

I have also attempted:

 background-size:contain;
 background-size:cover;
 background-size:100% 100%;
 background-postion: center center;

but unfortunately, no success yet.

Answer №1

I managed to get this code working smoothly across Firefox, Chrome, and Safari.

<img src="my.svg" style="width:100%;height:100%;position:fixed;top:0;left:0;bottom:0;right:0;" />

The key was ensuring that the SVG I used had preserveAspectRatio="none" specified at the root. Additionally, I either removed the viewBox attribute from the SVG or made sure it tightly enclosed the image content.

As shown in this example:

<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" viewBox="0 0 5 3">
    <desc>Flag of Germany</desc>
    <rect id="black_stripe" width="5" height="3" y="0" x="0" fill="#000"/>
    <rect id="red_stripe" width="5" height="2" y="1" x="0" fill="#D00"/>
    <rect id="gold_stripe" width="5" height="1" y="2" x="0" fill="#FFCE00"/>
</svg>

If possible, ensure you have control over the contents of the SVG files for optimal display. :-)

Answer №2

Check out this awesome solution using jQuery for manipulating SVG images without the need for <svg>

Here is the CSS:

#bgImage{
    position:absolute;
    left:0;
    top:0;
}

And here is the HTML:

<object width="10" height="10" id="bgImage" data="resources/runner.svg" type="image/svg+xml"></object>

Lastly, the JavaScript code:

//Function to resize the background image
function adjustImageSize($element){
    var imageRatio = $element.width() / $element.height();
    var screenRatio = $(window).width() / $(window).height();

    if(imageRatio > screenRatio){
        $element.height($(window).height());
        $element.width($(window).height()*imageRatio);
    } else {
        $element.width($(window).width());
        $element.height($(window).width()/imageRatio);
    }
}

Call the function on "onresize" and "onload" events to resize the image dynamically:

$(window).on('resize', function(){
    adjustImageSize($("#bgImage"));
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am experiencing difficulty locating the style.css file within my Node.js/Express application

I am currently working on a Node.js/Express app and I'm facing an issue where my browser is unable to find my style.css file, even though I am using a static file. Here is the directory structure: public -> css -> styles.css server -> server.js vi ...

How can I adjust the indentation in Angular Prime-ng's p-tree component?

In my project, I am utilizing the primg-ng tree component for the sidebar. Currently, the output is displayed as shown here: https://i.stack.imgur.com/kcSQt.png However, I am looking to maintain consistent indentation levels without any adaptive changes ...

flawless approach to showcasing visual content

I am a beginner in css. My goal is to showcase my images in an optimal way This is the HTML code I have: <div id="photos"> <h3>Title of the Photo</h3> <P class="like"><a href="#">Give it a Like</a& ...

Aligning Description Item components horizontally in antdLearn how to easily horizontally align Description

Currently, I am utilizing the `antd` Description components. In this scenario, when there is no `title` for the items, the value should be aligned to the left. You can see an example of this alignment in the image below: I have attempted to fix this issu ...

The layout causes issues with responsiveness on the Flask app page

I'm currently in the process of developing a web application and I've implemented a navbar.html file as the layout for each page using the following code: eachpage.html : {% extends 'navbar.html' %} {% block body %} <div class=" ...

Trouble with placing an absolutely positioned element using Tailwindcss

I am currently working on a project using TailwindCSS in which I have a logo positioned to the left and navigation to the right. Both elements are centered, but because the logo has a position of absolute, it appears in front of the navigation. I would lik ...

Showcasing a variety of product titles with the help of CSS

Since the HTML is hosted on another server and I have no control over it, how can I use CSS to style certain list items? For example, The HTML on the server side: <ol> <li>Coffee</li> <li>Milk</li> <li>Orange Juice< ...

JavaScript code to make titles slide in as the user scrolls

Looking for a better way to make all titles slide in upon scrolling instead of coding individually? Consider using a forEach loop! Here's how you can modify the code below: function slideInLeft() { document.querySelectorAll('.subtitle-left ...

Attempting to align navigation bar in the middle of the page

I'm facing some issues with centering the navigation bar on my website. I attempted to use a wrapper div to center it, but unfortunately, it didn't work out as expected. The only thing that seems to be working within that div is adjusting the lef ...

Difficulty understanding JavaScript sum calculations

I am currently working on a website project. Seeking assistance to enable an increment of one when clicked. Also need guidance on calculating the total price of items collected in a designated section under "number of items selected". Goal is to display ...

Activate animation when a user clicks on a link

Hey there, I'm a bit unsure about how to word this and I'm still getting the hang of StackExchange so I hope I've posted in the correct place. Currently, I am developing a mobile HTML5 app that utilizes Phonegap/Cordova (as well as Bootstra ...

Tips on how to align a wrapper-div in the center without affecting the positioning of the

I am looking to keep my page perfectly centered in the browser without affecting the content (similar to how align-text: center works). Specifically, I want to center my wrapper-div. How can I achieve this? Here is a simplified version of my current page ...

The text becomes jumbled and messy when the browser is resized

I came across this fantastic header design > https://codepen.io/rm/pen/ldhon <. However, I noticed that when the window is resized, the text ends up overlapping. In the demo provided, resizing the window too much causes the issue to become apparent, but ...

Adjusting the text of a button when hovering over it will also trigger a resizing of the

Currently, I am facing an issue where the bootstrap button's size changes when hovered over. My intention is to have the bootstrap button remain a fixed size while only the text inside it changes using javascript for mouseover and mouseout events. How ...

Mastering the Art of Displaying Every Side of a Spinning Cube Using HTML and CSS Animations

As I navigate the online world, my goal is to create a dynamic animation of a rotating cube with an image on each face. Despite my efforts, I am struggling to display all faces simultaneously, especially the front and back faces. I have explored various so ...

Background color vanishes (occasionally) on the contact section of my website when viewed in Chrome

My contact page has an issue that only occurs in Chrome, where the background disappears most of the time. This problem is not present in Firefox, Edge, or Safari on my TA's MacBook, but interestingly, hovering over a box resolves the issue on her dev ...

Does the CSS overflow property affect the borders of an element?

Consider a situation where a "div" element has a border applied to it. When the overflow rule is set to 'hidden', any content that falls directly on the border will vanish. Is there a solution for this issue? It is crucial in my case to ensure t ...

include a button next to the input field

As you reduce the browser window size, you may notice a different layout designed specifically for iPhone. One question that arises is how to add a button next to the search text box dynamically using JavaScript. The issue at hand is that the text box is b ...

Stopping all animations with JQuery animate()

I have a question about stopping multiple animations. Here's some pseudocode to illustrate my situation: CSS #div1 { position: absolute; background-image: url("gfx/cat.jpg"); width: 60px; height: 70px; background-size: 50%; b ...

How can I create a custom elevation for a Vuetify v-menu?

I'm currently working with vuetify and v-menu as outlined in the official documentation here https://vuetifyjs.com/en/components/menus/ I'm struggling to figure out how to apply elevation only on the bottom left and right corners. When I add a ...