The Ultimate Guide to Setting up SVG's Viewbox, Width, and Height for Scalability and Responsiveness

As a beginner in SVG design, I find it challenging to scale, zoom in/out with the container and ensure responsiveness across different devices.

I wonder if it's possible to create an SVG that adapts to all device sizes and effectively handles browsing zoom functionality.

So far, I've experimented with viewport and viewbox settings for each breakpoint.

For example, on Desktop, I have an SVG that fits within a container and should scale and zoom in/out accordingly (svgClass).

.svgClass {
 background-image: url('assets/svg/desktop-svg.svg');
 width: "100%";
 height: 800px;
 position: absolute;
}

<div class="svgClass"></div>

Sample SVG

---desktop-svg.svg---

<svg width="1400" height="800" viewbox="0 0 1121 641">
-----
</svg>

The SVG displays well at 100% browser zoom, but becomes displaced when zoomed in or out.

To address zoom in, I increased the viewport height to 1400 and width to 800 compared to the viewbox (0 0 1121 641), which worked for zooming in but not out.

I've attempted removing width and height from the viewport and experimenting with auto and 100% settings, but haven't achieved success.

How can I design an SVG that scales with the container and remains responsive? Also, do I need to set up viewport and viewbox configurations for each device?

Answer №1

Let me provide an example where SVG is contained within the parent container. In this scenario, the parent container will appear as a gray square. It's important to note that the SVG file should not specify width and height in the header but rather use viewBox for adaptability.

I've utilized an input element to demonstrate how adjusting the width of the parent container proportionally alters the dimensions of the SVG:

.container {
width: var(--w1,60px); 
background:#EAEAEA;
}
<div>
    <input type="range" 
           min="60" 
           max="600" 
           oninput="document.querySelector('.container').style.setProperty('--w1', this.value + 'px');" 
           value="0">
    <span>width Container</span><br> 
</div>
<div class="container" >
    <svg  viewBox="0 0 120 120">    
        <defs>
            <mask id="msk1">
                <circle class="maskCircle" cx="60" cy="60" r="40" fill="none" 
                        stroke="white" stroke-width="8" 
                        stroke-dashoffset="0" stroke-dasharray="251.2">
                    <animate attributeName="stroke-dashoffset" dur="3s" 
                             values="251.2;0" fill="freeze" 
                             repeatCount="indefinite" />
                </circle>
            </mask>
        </defs>
        <circle class="background" cx="60" cy="60" r="40" fill="none" 
                stroke="#E4E4E4" stroke-width="8" />
        <circle class="default" cx="60" cy="60" r="40" fill="none" 
                stroke="black" 
                stroke-width="8"
stroke-dasharray="3.14" 
                stroke-dashoffset="40"  
                mask="url(#msk1)">

        </circle>
    </svg>
</div> 

UPDATE

<div>
<input type="range" min="60" max="600" oninput="document.querySelector('.container').style.setProperty('--w1', this.value + 'px');" value="0"><span>width Container</span><br> 
</div>

The aforementioned lines can be removed from the application as the input was solely used for illustrating the adaptive nature of the SVG when resizing the parent container.

Useful insights:

  1. While developing an adaptive SVG application, set the viewBox ="0 0 200 200" with dimensions matching the smallest screen size of the device. When creating graphics in a vector editor, ensure not to exceed the document boundaries - typically around 200x200px.

  2. If width and height aren't specified for the SVG, it will automatically adjust to fit the entire screen of the device.

<svg xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 200 200" >

For instance, at a screen resolution of 1400px, the SVG would scale up by a factor of 7.

  1. If you wish for the SVG to occupy only one quarter of the parent container, specify both the width and height as 25%:
<div class="container" style="width:25%; height:25%;"> 
   <svg xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 200 200" >
    .... 
    </svg>
</div>  

Answer №2

To ensure your SVG auto-fits inside its container, remove the "width" and "height" attributes and solely focus on adjusting the viewBox numbers. This way, conflicting with the container's dimensions (e.g., a DIV) will be eliminated.

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

The struggle of positioning two divs in alignment

In my HTML code, I have a div container named row3red3. Inside this container, there are two divs: left (.row3red3slika) and right (.row3red3info). I am facing an issue where I cannot position the right div .row3red3info on top, inline after the image. I ...

Malfunctioning Bootstrap collapse feature

I am experiencing an issue with my modal that contains 2 blocks. When I click on the .emailInbound checkbox, it opens the .in-serv-container, but when I click on the .accordion-heading to reveal the comment section, the .in-serv-container collapses. What c ...

Unable to apply color changes with jQuery

As I delve into learning jQuery, I encountered an issue while attempting to change the color of a tr element. Strangely, I was successful in updating other CSS attributes like font-style. According to my understanding so far, we use the following syntax to ...

Retrieve the href attribute from a hyperlink positioned above a different element using Selenium

My challenge in using selenium is to extract an href from a link buried within numerous tags! The only identifiable detail I can work with is the presence of the text "Test text!" in the h3 tag as shown in the example below: <a href="/li ...

Show a Pop-Up When a Key is Pressed

My website popup features a 'Close' button in the top right corner, a text section with a background image, and a 'Print' button at the bottom. The popup automatically appears when the page loads. However, once closed, there is currentl ...

Tips for updating the date format in Material UI components and input fields

Is there a way to customize the date format in Material UI for input text fields? I am struggling to format a textField with type 'date' to display as 'DD/MM/YYYY'. The available options for formatting seem limited. It would be helpful ...

How to arrange table data in Angular based on th values?

I need to organize data in a table using <th> tags for alignment purposes. Currently, I am utilizing the ng-zorro table, but standard HTML tags can also be used. The data obtained from the server (via C# web API) is structured like this: [ { ...

Exploring Laravel 4: Navigating Tables with Relational Models

Edit: error fixed I am managing two interconnected Models: Project and Task. Their relationship is defined as follows: Project.php class Project extends Eloquent { public function tasks() { return $this->hasMany('Task'); ...

Tips for maintaining tab state using Angular Material

In my Angular 8 application with Angular Material, I have implemented four tabs where each tab allows editing. However, when going back from the edit mode to the tabs, I want the last selected tab to remain selected. My approach so far is as follows: exp ...

Generate a bill based on items in a virtual shopping cart

I am having trouble with formatting the output of a shopping cart to an invoice. The data is displaying, but it's not showing up correctly. Here's the code snippet: <table class="table table-striped"> &l ...

I am looking for an image search API that supports JSONP so that users can easily search for images on my website

I am currently in the process of creating a blog platform. My goal is to allow users to input keywords on my site and search for images directly within the website. This way, I can easily retrieve the URL of the desired image. ...

Creating an indentation on one side of a div using CSS for a visually appealing effect

https://i.stack.imgur.com/io6m0.jpg I'm in the process of trying to create two shapes using CSS. I've been able to almost achieve the first shape on the left, but it extends out too far. As for the second shape, I'm having difficulties cre ...

Tips for customizing the appearance of a redux-tooltip

After implementing the redux-tooltip from this GitHub repository, I wanted to customize its styling to better align with my application's design. However, I realized that the Tooltip-Component's divs do not have any identifiers or class names, ma ...

Using PHP to generate a table populated with generic elements from an array

How can I create a dynamic table in PHP that can handle any generic array with different keys and values, including nested arrays? I want to use the same table structure for various arrays regardless of their content. Any advice on achieving this flexibili ...

What could be the reason for my jQuery script not functioning properly?

<script> var currentLevel = 0; $(document).ready(function(){ $("#tolevel_" + (currentLevel+1) ).click(function(){ $("#level_" + currentLevel).hide(500,'swing', function(){ $("#level ...

Easily create an HTML page from a multitude of intricate JavaScript objects with this convenient method

In my project, I am looking to dynamically generate an HTML page based on JavaScript objects and then present it to the user. For example: var mybutton = { id: 'button_1', x: '0', y: '0', width: '100', h ...

When an anchor link is dynamically created, the `click()` method does not activate the click event

After creating an anchor element using the document.createElement('a') method, I encountered an issue where the click event was not being triggered as expected. To provide more context, refer to the code snippet below: var link = document.create ...

The Bootstrap glyphicon content breaks when using ASP.NET MVC minification

When working with asp.net, I noticed that minification tends to disrupt the display of bootstrap UTF symbols. For example, here is what it looks like in the original file: .glyphicon-edit:before { content: "\e065"; } And here is how it appears in ...

Having issues with AngularJS ng-if when implemented within a Form

Is there a way to hide my form after it has been submitted using ng-if? I am facing an issue where clicking the 'See' button toggles the form on and off, but the same functionality does not work with the 'Add' button. Any insights on wh ...

What is causing the role="status" attribute to malfunction?

I'm having an issue with the role="status" attribute in my code. When using a screen reader, the paragraph text doesn't get read once it's appended to the body. index.html: <!DOCTYPE html> <html> <head> <title> ...