While SVGs are inherently responsive due to their vector nature, you can further customize their behavior based on screen size and device capabilities using media queries.
Basic Syntax
HTML
<svg width=”100%” height=”100%” viewBox=”0 0 200 200″>
<circle cx=”50″ cy=”50″ r=”25″ fill=”blue” />
</svg>
CSS
@media only screen and (max-width: 600px) {
svg circle {
r: 20;
}
}
In this example, the circle’s radius will be reduced to 20 pixels on screens narrower than 600px.
Key Considerations
- viewBox attribute: The viewBox attribute on the <svg> element defines the coordinate system within the SVG. It’s essential for responsive design as it allows you to scale the SVG content relative to its dimensions.
- Relative units: Use relative units like em or rem for dimensions within SVG elements to ensure they scale with the surrounding content.
- CSS media queries: Use CSS media queries to target specific screen sizes and apply different styles to your SVG elements.
Additional Techniques
- Responsive SVG Sprites: Combine multiple SVGs into a single sprite and use CSS to display specific elements based on screen size.
- SVG Animation: Use SMIL or JavaScript to create animations that adapt to different screen sizes.
- SVG Filters: Apply filters to SVG elements to create visually interesting effects that can be adjusted based on screen size.
Example: Responsive SVG Sprite
HTML
<svg width=”0″ height=”0″>
<symbol id=”icon-star”>
</symbol>
</svg>
<svg width=”200″ height=”100″>
<use xlink:href=”#icon-star” x=”50″ y=”50″ />
</svg>
CSS
@media only screen and (max-width: 600px) {
svg use {
width: 20px;
height: 20px;
}
} By understanding how to use media queries and other techniques with SVGs, you can create responsive and visually appealing designs that adapt to different screen sizes and devices.