How to Maintain SVG Aspect Ratio in CSS Grid with Dynamic Content?
Can someone help me understand I keep running into I'm sure I'm missing something obvious here, but I'm optimizing some code but After trying multiple solutions online, I still can't figure this out. I've been researching this but Quick question that's been bugging me - I'm working on a personal project and I'm working on a personal project and I'm working on a responsive layout using CSS Grid, and I'm trying to display SVG icons that should maintain their aspect ratio regardless of the grid cell size... However, when the content in the grid changes dynamically, the SVGs often get distorted or cropped. I've set the SVGs to have a width of 100% and height of auto, but that doesn't seem to solve the scenario. Here's a simplified version of my CSS and HTML: ```html <div class="grid-container"> <div class="grid-item"> <svg class="icon" preserveAspectRatio="xMidYMid meet" viewBox="0 0 100 100"> <circle cx="50" cy="50" r="40" fill="blue" /> </svg> </div> <div class="grid-item"> <svg class="icon" preserveAspectRatio="xMidYMid meet" viewBox="0 0 100 100"> <rect width="80" height="80" fill="red" /> </svg> </div> </div> ``` ```css .grid-container { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; } .grid-item { background: #eee; padding: 20px; position: relative; overflow: hidden; } .icon { width: 100%; height: auto; } ``` When the grid items resize, sometimes the SVGs either overflow their containers or get squished in a way that doesn't respect their aspect ratios. I tried setting the `overflow: hidden;` on the `.grid-item`, but this only results in part of the SVG being cut off. I also experimented with setting fixed sizes on the SVGs, but that leads to responsiveness issues on smaller screens. I received an behavior in the console related to the `viewBox` not being valid when the SVG is scaled beyond its original size. Any tips on how I can adjust my CSS or SVG attributes to keep the aspect ratio intact while still being responsive? Is there a better approach? My development environment is Windows. What am I doing wrong? Am I approaching this the right way? I'm using Html/Css 3.11 in this project. Any ideas what could be causing this? Has anyone else encountered this? This is for a application running on Ubuntu 20.04. Any pointers in the right direction? Any advice would be much appreciated. I'm on Ubuntu 22.04 using the latest version of Html/Css. I'd be grateful for any help.