CodexBloom - Programming Q&A Platform

CSS Scaling implementing SVG Icons in a React App Using Styled Components

πŸ‘€ Views: 49 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-07
css react svg styled-components javascript

I'm migrating some code and I'm working with a question with scaling SVG icons in a React application where I'm using Styled Components for styling... My SVG icons are supposed to resize dynamically based on the parent container's size, but they seem to be exploring at their original size, which is causing layout issues on different screen sizes. I've tried using both `width` and `height` properties set to `100%`, but the icons don't seem to respond to the changes in the parent container. Here's the relevant part of my component: ```javascript import styled from 'styled-components'; const IconContainer = styled.div` width: 50%; height: auto; display: flex; justify-content: center; `; const SvgIcon = styled.svg` width: 100%; height: 100%; `; const MyComponent = () => ( <IconContainer> <SvgIcon xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"> {/* SVG Path */} <path d="..." /> </SvgIcon> </IconContainer> ); ``` Despite setting both the container and the SVG to use percentages, the SVG remains fixed at the size defined in its `viewBox`. I even tried adjusting the `preserveAspectRatio` attribute of the SVG, but it didn’t help. The expected behavior is that the SVG should fill the container proportionally as its size changes, but instead, it’s not scaling correctly. Has anyone encountered similar issues with SVGs in React and Styled Components? What could I be missing here? I'm currently using React 18.0.0 and styled-components 5.3.5. For reference, this is a production CLI tool. What am I doing wrong?