Creating a CSS div that can be resized while maintaining a constant aspect ratio

My goal is to create a resizable SVG with a fixed aspect ratio by placing it inside a <div> that adjusts to the size of the SVG. I'm using the Rust Seed library, so although my code isn't in JavaScript, you should still be able to understand the concept:

div![ // wrapping div
    style!{
        St::MaxWidth => "100%";
        St::MaxHeight => "100%";
        St::Resize => "both";
        St::Overflow => "auto";
    },
    svg![ // contained svg
        style!{
            St::BackgroundColor => "gray";
        },
        attrs!{
            At::Width => "100%",
            At::Height => "100%",
            At::ViewBox => format!("0 0 {} {}", width, height),
            At::PreserveAspectRatio => "xMinYMin meet",
        },
        text![ // svg text
            "Example SVG"
        ],
    ]
]

I've been facing an issue where the wrapper does not dynamically match the size of the SVG. I've attempted using "min-content" and "max-content" on the MaxWidth and MaxHeight attributes, but it hasn't produced the desired result. How can I make this setup work as intended?

Here's the current behavior: https://i.sstatic.net/55EGh.gif

Answer №1

To address this issue, one approach is to utilize the properties resize: horizontal and height: auto on the container. It is also important to exclude the height attribute on the svg element (the use of the width attribute is unnecessary as well).

div![
    style!{
        St::Resize => "horizontal",
        St::Overflow => "auto",
        St::Height => "auto",
    },
    svg![
        attrs!{
            At::ViewBox => format!("0 0 {} {}", width, height),
            At::PreserveAspectRatio => "xMinYMin meet",
        },
        text![
            "Example SVG"
        ],
    ]
]

Nevertheless, a drawback of this solution is that it changes the cursor to e-resize, which may not enhance user experience. Various attempts have been made to revert the cursor appearance back to its default state, but none have proven successful thus far.

https://i.sstatic.net/tVlhE.gif

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 ValidatorCalloutExtender is failing to display the CSS correctly

After successfully customizing the style of my ValidatorCalloutExtender on a RequiredFieldValidator to a more 'Modern UI', I encountered an issue when deploying it to the production server. Despite testing it on multiple browsers with satisfactor ...

Having trouble retrieving data from getters in the Vue store while inside a template

Within my component, I have set up computed properties that are supposed to display text for blopp and blipp. However, while blopp is working fine, blipp is not showing anything. The end goal is to have blipp generate a list of strings from the store state ...

Can @keyframes percentage be determined using a CSS variable?

My animation is responsive to the number of characters present It functions properly with 20 characters: const text = '20 characters length' const speed = 0.1 const $container = document.querySelector('.wave') $container.style.setPr ...

Troubleshooting issue: Incompatibility between NODE.JS Passport and mongoose

Currently, I am diving into the world of Node.js and exploring all its features with the help of Scotch's tutorial (https://scotch.io/tutorials/easy-node-authentication-setup-and-local). Following the tutorial, I implemented what was suggested, which ...

Issue with using float-right in Bootstrap v4. [Alternative to pull-right]

I am currently using the most recent version of Bootstrap, which is v4.0.0-beta.3. I am having trouble getting elements to align properly according to the official documentation. Despite searching online for solutions, I have not been able to find any that ...

I'm having trouble getting my state to update in React when using useState

I am facing an issue with rendering a component that has a route using react router. The first component contains a button, and upon clicking it should render another component with state passed down from the initial component. However, even though the pag ...

Utilizing JavaScript variables to generate a custom pie chart on Google

Greetings! I must admit that I am a novice, especially when it comes to JavaScript. My background is mainly in PHP. Recently, I came across a fantastic pie chart created by Google https://developers.google.com/chart/interactive/docs/gallery/piechart I a ...

Designing visual representations using the Canvas elementorGenerating graphic content

I want to design a creative text image where multiple characters come together to form a word, like "The Matrix", within an animated canvas with a matrix effect. The challenge I'm facing is figuring out how to display the text inside the canvas and th ...

Guide on retrieving the content type field value in Drupal and transferring it to a JavaScript file

In my custom Drupal theme, I have included a field for a SoundCloud URL with the machine name (field_soundcloud_url_). I am attempting to use a JavaScript file that will function based on the value of this variable. However, it seems to not be working as e ...

How can I avoid C3.js legends from overlapping when hiding or showing a div?

Every time I visit a specific page, a simple chart is automatically generated: function displayOptions() { $("#div1").show(); chartRef.flush(); } function displayChoices() { $("#div1").show(); } $("#div1").hid ...

In React, the Textarea component that displays the character count only updates its value after a page reload

Contained within this element is the following component: import React, { useEffect, useState } from 'react'; import { TextareaTestIds } from '../utils/test-ids'; export interface TexareaProps extends React.TextareaHTMLAttributes<H ...

What is the best way to ensure my Bootstrap 4 popup closes when the "Esc" key is pressed on the keyboard, especially when the popup contains a YouTube video as an embedded iframe that is currently paused?

We have integrated Bootstrap 4 into our website, with a feature that opens a popup when clicking on an image. This popup contains an embedded YouTube video. A problem arises when trying to close the popup by pressing the "Esc" button after interacting with ...

I am struggling to find a recurring element within a BeautifulSoup object

The challenge that is currently plaguing me is absolutely driving me up the wall. I am attempting to extract some text from the Pro Football Reference website. The specific data I require can be found within a td element labeled as qb hurries situated in ...

The HTML image tag is malfunctioning on a Windows system

I'm currently updating an HTML page and trying to add an image using the img tag. <img src="file:///C:/wamp/www/images/Sat.png" class="img-circle" alt="User Image"/> However, it doesn't seem to be working! ...

Sending an email using Angular is a straightforward process that involves utilizing the built

I need help figuring out how to code a function in Angular or TypeScript that will open Gmail when a specific email address is clicked. I've tried different methods but haven't been successful so far. ...

Can you please provide me with the correct JQuery syntax to verify if an element already exists within an array? Below is an uncomplicated example to illustrate

I decided to create a JS Fiddle to experiment with various techniques. The main query presented is: "What is the correct method for displaying only 4 unique items in the dropdown list, while avoiding duplicates of the same item?" My if statement implemen ...

Is there a way to showcase the information from an xml file within html divs using an ajax request?

I am currently developing an online platform for managing contacts, and I am looking for a way to showcase contacts stored in an XML file within HTML div elements using only an AJAX call. The structure of my XML file is as follows, and I aim to create se ...

Implement a dropdown menu in Vue.js using data fetched from an ajax request

I am looking to utilize ajax calls in conjunction with vue.js to dynamically populate the options for a drop-down menu. Here's an example of what I currently have: <select v-model="selected"> <option v-for="option in options" v-bind:valu ...

Tips for Angular JS Single Page Applications: Implementing Angular Controllers to Invoke Angular Services

Currently, I'm in the process of building a Node.js Application using Angular.js and Express.js. My goal right now is to populate a list with customer names and addresses by using this code snippet: var mylist = new generic.list(); mylist.add({name ...

Do bluebird promises require the use of async keyword?

Currently, I am looking to integrate Bluebird promises into my project which is built using NodeJS, Express, and Mongodb. Below is an excerpt from my model file: const mongoose = require('mongoose') // Blue Bird mongoose.Promise = require(&apo ...