Stacking SVG elements can lead to distortion effects

Currently experimenting with the innovative SVG stacking method to integrate multiple icons into a single file, reducing the browser's HTTP requests. The details of this technique can be found in depth here.

In essence, it involves placing numerous SVG elements within one SVG file and utilizing CSS styles to hide all icons except for the one currently selected for display. To choose the visible icon, the CSS :target selector is employed.

The approach is successful for me, except when stacking multiple icons, peculiar distortions occur in the displayed image despite hiding all other icons.

In my example, I decided to stack only two icons: a US flag and a UK flag.

The simplified SVG file looks like:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<svg id="svg153" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://www.w3.org/2000/svg" height="480" width="640" version="1.1" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/">

    <svg:style 
        xmlns:svg="http://www.w3.org/2000/svg" type="text/css">
        .i { display: none; }
        .i:target { display: block; }
    </svg:style>

    <svg:svg id="uk" xmlns:svg="http://www.w3.org/2000/svg" class = "i" height="480" width="640" version="1.1">
       <!-- SVG elements to draw UK flag -->
    </svg:svg>

    <svg:svg id="us" xmlns:svg="http://www.w3.org/2000/svg" class = "i" height="480" width="640" version="1.1">
       <!-- SVG elements to draw US flag --> 
    </svg:svg>
</svg>

Note that the CSS is embedded within the SVG file, inside a <svg::style> element. The CSS simply consists of:

.i { display: none; }
.i:target { display: block; }

In this manner, any svg::svg element with class="i" is automatically hidden unless targeted specifically in the SVG URL. Thus, to display a US flag icon, the following HTML snippet would be used:

<img 
    src="flags.svg#us" 
    width="80" 
    height="60" 
    alt="SVG Stacked Image" 
/>

Similarly, for displaying the UK flag, the code would be changed to src="flags.svg#uk"

Everything works smoothly, but a strange image distortion occurs when stacking images in both Firefox and Chrome.

Here's an image of the undistorted US flag after removing the hidden UK flag from the SVG file:

As evident, it appears fine.

However, when overlaying it on top of the UK flag, the image seems distorted as shown below:

The resultant image is oddly skewed - resembling what happens to low-quality JPEGs with compression artifacts.

Why does this distortion occur? All other images stacked with the US flag are invisible, so why do they impact the visible icon?

Extensive searches on Google uncovered various issues and pitfalls associated with SVG stacking primarily related to cross-browser compatibility. Despite successfully working across most modern browsers up to and including IE9, the distortion persists in both Firefox and Chrome, indicating a probable mistake on my part rather than a cross-browser issue.

Therefore, what exactly causes this unusual distortion post the application of the SVG stacking technique?

Answer №1

Unfamiliar with stacking and targeting icons? No worries! Here are two straightforward methods that might make things easier for you.

  1. If you have individual SVG icons sourced from the internet or saved on your computer:
    • Visit 'icomoon.io', a website where you can select icons from online libraries or upload custom SVG icons from your computer.
    • Go to ''
    • Use the 'import icons' feature to upload your own icons.
    • Scroll to the bottom of the page and click on 'Add Icons From Library…' to choose icons from online libraries.
    • With the 'select' tool (located at the top), pick multiple icons of your choice.
    • Once you've selected all the desired icons, hit the 'Generate SVG,PNG,PDF' button at the bottom.
    • To merge all the icons into one file, click on the 'settings icon' next to the 'Download' option in the first button on the bottom left corner.
    • Select 'Include Tiles (CSS Sprite)' from the settings menu.
    • Adjust margins and specify the number of icons per row according to your preference, then download the combined sprite along with its XML code in demo.html and CSS definitions in style.css.
  2. If you already have a single SVG file containing multiple icons created using software like Adobe Illustrator:
    • Simply import the file to icomoon.io and click on the 'Generate SVG,PNG,PDF' button to download the sprite XML file.

Answer №2

After experimenting with my own basic svgs, I didn't encounter any strange distortions. It seems likely that the issue lies with the svgs specific to the UK and US.

http://pastebin.com/dxVtTQKF

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

Ways to align the `<ol>` number at the top vertically

I'm having trouble aligning my <ol> numbers vertically at the top of the list. I've created a sample on CodePen. ol { list-style-type: decimal-leading-zero; font-size: 11px; } a { font-size: 80px; tex ...

Aligning the wp_nav_menu vertically within the site-header

Is there a way to vertically center the WordPress function wp_nav_menu in my site header? Although I followed the learnWebCode tutorial for the menu, I am struggling to implement it successfully. Is there anyone who can provide guidance or a solution? ...

Show a collection of files in a table format

Here is the current code I have: index.html <!DOCTYPE html> <html> ... </form> </div> </body> </html> And here is my code.gs function doGet() { return HtmlService.createHtmlOutputFromFile('index'); } ...

What impact does including a parent View Tag have on the styling in React Native?

Why does adding a View parent break my styles? Could React Native's View tag have default styles that I'm not aware of? Displayed below is the Button component along with screenshots demonstrating the difference when using and not using the View ...

Modifying the color of Bootstrap icons

When I use PHP code to print this icon into a table, it looks like this: echo '<button Onclick="" style="border: none; background: none; color:green"><a title="Reenviar" data-toggle="tooltip"><i class="material-icons">&#xE0BE;&l ...

Generate a new Div dynamically, positioned higher than the rest

Once a second, this script will utilize AJAX to open a new page and display the contents in a dynamically created div on this page. However, the issue is that the new divs are stacking under each other, and I would prefer them to be added at the top instea ...

Repairing the base navigation interface and correcting the hyperlink to redirect to a different webpage

Can anyone assist with aligning my bottom navigation bar and fixing a link issue on both navigation bars? I've been struggling to center it. Do you think using padding could solve the problem? I've tried guessing the pixel count, but to no avail ...

Emphasize a feature within a dynamic DIV

How can I highlight the span(class="tiny") element individually when its containing div is active or clicked? I have attempted to highlight the tiny span element without success, as only the entire div was highlighted. Here's the code snippet I' ...

Navigate through an overflowing element in react/next

I have a component with a fixed width and overflow-x-auto. I want to hide the scroll bar and replace it with arrow buttons for scrolling left and right. How can I add this functionality to my component? Here is the code for my component: <div className ...

Automatically create CSS properties for left and top using absolute positioning

When looking at these websites as models: On each of them, I noticed that there is a well-organized column of boxes for every post. I attempted to recreate this using various methods, but couldn't achieve the exact layout on my own website. It seems ...

An error that cannot be recovered from occurred: Trying to access a method called viewConfessionLikes() that is

Greetings! I am currently facing an issue on my website where the page displaying the most liked post is showing an error message: Fatal error: Call to undefined method Confession::viewConfessionLikes() on line 55 Unfortunately, this page is not showing a ...

Using JavaScript and Tampermonkey to convert strings from an HTML element into an array

I am trying to change the names of months into numbers and place them in a table cell on a website. I thought using an array would make it easier to reference the month names by their corresponding array numbers, allowing me to add table tags before and af ...

Tips for resolving the issue of receiving a warning about passing "onClick" to a "<Link>" component with an `href` of `#` while having "legacyBehavior" enabled in Next.js

My current project is displaying a lot of warnings in the browser console and I'm unsure about the reasons behind it. The warnings include: "onClick" was passed to with href of /discovery/edit but "legacyBehavior" was set. The l ...

Using JQuery to visually enhance the menu selection by displaying an image and altering the background color upon hovering

Hello fellow JQuery/Javascript beginners! I recently put together a menu and wanted to add some interactive elements. Specifically, I want the background color to change when a user hovers over an item (simple enough with CSS), but I also want to include a ...

What is the best way to post an image using nodejs and express?

Recently, I've been working on a CMS for a food automation system and one feature I want to incorporate is the ability to upload pictures of different foods: <form method="post" enctype="multipart/form-data" action="/upload"> <td>< ...

leveraging the power of JQuery and Ajax for submitting a form

I am looking to implement ajax functionality for form submission I want to achieve this using radio buttons instead of a submit button Essentially, when a radio button is clicked, the form should be submitted or posted My PHP page needs to determine whi ...

What is the process for utilizing jQuery's advanced ticker feature to extract content from a text file?

I am currently implementing this code on my website: <script> var file = "http://newsxpressmedia.com/files/theme/test.txt"; function getData(){ $.get(file,function(txt){ var lines = txt.responseText.split("\n"); for (var i = ...

It is important for the CSS :active state to transition to an "inactive" state after a certain period of

For mobile, I utilized the :hover and :active pseudo-classes to create a transition effect when tapping on a tab that enlarges the elements for more information. However, I am seeking a way for the activated element to return to its original state after a ...

Can you explain the significance of the "style.css?ver=1" tag?

Recently, I noticed that certain websites incorporate a CSS tag such as style.css?ver=1. Can you explain the significance of this? What exactly is the purpose of adding ?ver=1 to the CSS tag? Could you provide instructions on how to implement this in cod ...

Restrict the size of the numerical input in AngularJS

<input class="span10" type="number" max="99999" ng-maxLength="5" placeholder="Enter Points" ng-change="myFunc($index)" ng-model="myVar"> This code snippet adjusts the value of form.input.$valid to false if the number entered exceeds 99999 or is long ...