Creating an SVG element that adjusts to the size of its parent container: tips and tricks

I'm attempting to achieve the following:
Displaying an SVG square (with a 1:1 aspect ratio) inside a div element. When the width of the div is greater than its height, the square should adjust to fit within the container based on the height (red box represents the div, green box represents the svg square):
https://i.sstatic.net/GMxYw.png

When the height of the div is greater than the width, the square should adjust to fit within the container based on the width:
https://i.sstatic.net/fnWS4.png

This can be easily achieved by specifying the size of the svg view port. However, if I remove the size of the svg view port and instead add the size to the parent div (red box), it fails to consider the height of the container, resulting in the following image: https://i.sstatic.net/agINk.png https://i.sstatic.net/YoCTt.png

Is there a way to make the square responsive to the container height? Below is my code:

#main {
  width: 400px;
  height: 100px;
  border: 4px solid red;
}
<div id="main">
  <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid Meet">
    <rect x="0" y="0" width="100" height="100" fill="green"/>
  </svg>
</div>

Answer №1

To ensure the SVG fills its container, simply set the width and height attributes to "100%". You can do this directly in the SVG element or through CSS.

Also, make sure to correct the following attribute issues:

  • The viewBox values should not include commas.
  • It should be preserveAspectRatio, not preserveAspect, and use meet, not Meet.

#main {
  width: 400px;
  height: 100px;
  border: 4px solid red;
}
<div id="main">
  <svg width="100%" height="100%" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet">
    <rect x="0" y="0" width="100" height="100" fill="green"/>
  </svg>
</div>

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

Steps for creating a sleek vertical slider with transitional effects using JavaScript and HTML

Take a look at my code snippet: <table> <tr> <td onclick="shownav()">Equations of Circle <div id="myDownnav" class="sidenav"> <a>General Info</a> <a>In Pola ...

When you hover over the vertical sidebar menu in Bootstrap material design, a submenu will appear

Looking to create a three-column display that functions as one submenu when hovering over each menu item? <div class="container"> <div class="row"> <div class="col-sm-4"> <ul class="vertical-nav"> <li>&l ...

Loading screen while all files and audio are being loaded

My JavaScript code is responsible for displaying and playing audio on my website. Unfortunately, the load time of the page is quite slow. To address this issue, I decided to follow a tutorial on installing a preloader, which can be found at . Although I ...

Implementing a two column stacked layout with Susy, similar to the design of Twitter's interface

Having worked extensively with Susy, I recently encountered a unique use case that has left me puzzled. To illustrate my point, let's take Twitter as an example. If we observe their website layout, they have a standard three-column design with a brea ...

What is the best method for utilizing the jQuery Selector in this particular web application?

I have been attempting to figure out how to select a delete icon within my personal web application. delectIcon HTML <main> <div class="container"> <div class="tabs"> <a href=""><p><span class="act ...

Guide to utilizing JavaScript for a basic gaming experience

Looking to incorporate multiple divs that will vanish upon being clicked, while also increasing the score by 1 through javascript. Any suggestions on how to accomplish this? ...

Using a background image in CSS for horizontal rules can override other styling rules

Encountered an unusual CSS bug: After using background-image to style hr, none of the subsequent rules or selectors are displaying on the page: hr { border: 0; height: 1px; background-image: -webkit-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0 ...

I desire a smooth fade-in transition for the background image when the addClass function is

If the background color is set to header-fixed-position, the color will fade in. However, if the background is an image, the image will not fade in. Apologies for my lack of proficiency in English. Please refer to the sample code below. Try removing the c ...

The vertical menu was added, but the text did not align properly

I pasted a sidebar from a different source https://i.stack.imgur.com/jkYWz.png My goal is to have the text appear at the top of the page, similar to this example https://i.stack.imgur.com/1aR5s.png After adding this line, my text is displaying at the b ...

Troubleshooting problems with the height of nested DIV elements

Issue I am attempting to replicate the layout depicted in the image below. The black area represents the body with id="library", the grey div is id="body" (which is not visible due to lack of margins for inner divs), the light blue div is id="sideBar", th ...

Clickable links and compliant W3C coding

Recently, I have encountered errors in the W3C validator due to the presence of "name" attributes in some <a> tags in my document. The validator flagged these attributes as obsolete. I am curious to know when and why this happened? Additionally, I n ...

What about a lightbox with enhanced jQuery features?

As a newcomer to jQuery, I've never experimented with lightboxes before. However, I was tasked with creating something fun for April Fools' Day at work. Naively, I accepted the challenge thinking it would be simple, but now I find myself struggli ...

What causes a CSS layout to become misaligned when a line border is added?

After reviewing solutions provided in an answer to a previous question, I attempted to implement a line border within a div nested inside another div. Unfortunately, this implementation caused the div to become distorted. Why did this happen? Markup: &l ...

What is the best way to turn off default CSS styling in KendoUI?

I am facing an issue in my application where I am using global CSS definitions for "INPUT", "SELECT", and other elements. The problem arises when I try to incorporate KendoUI widgets, as they override my default CSS styles. For instance, my CSS code looks ...

How to align a div with a background in CSS to the center

I'm attempting to center a text and an icon, but the icon is set within a background. How can I center the text and position the icon just to the left of the text? Here is the link to the fiddle with the code: jsfiddle <div class="error divErro ...

Utilizing Python and Selenium to Locate an Element Based on Text Within a Span Class

My challenge is locating an element without any ID or distinctive identifiers. The HTML code structure resembles the following: <div class="item_select"> <span class="item_selection_number">A </span> </div> <div class="item_ ...

Can a Dashcode Webkit Web app be transformed into traditional HTML and CSS?

I have developed a blog using Dashcode, incorporating HTML, CSS, and Javascript to pull data from an xml file. It's pretty simple... My perspective on this is: 1. JavaScript should be compatible with all browsers (with some variations). 2. I may need ...

Tips for maintaining consistent width of a div:

My current project involves designing a website that displays various quotes, with each quote rotating for a specific amount of time. However, I'm facing an issue where upon loading the page, the first quote triggers the appearance of a scrollbar, mak ...

Having trouble with the CSS drop down menu in Internet Explorer 10?

Can you assist me with a challenge I am facing? I am currently working on creating a dropdown menu using only HTML and CSS. However, I have encountered an issue where the hover function is not functioning properly in IE10, although it works perfectly fine ...

Browsing using the "touchmove" feature feels extremely laggy

I implemented a workaround to achieve "position:fixed" on mobile devices, specifically my Android device. This involved creating two divs with heights that combined to match the screen height through JavaScript, and adding touch listeners to the bottom div ...