The recommendation to specify width and height attributes in pixels for SVG elements stems from historical rendering requirements and legacy browser behavior, but modern practices prioritize responsiveness and flexibility. Here's a nuanced breakdown:
1. Why Pixels Were Historically Recommended
-
Default Rendering Behavior:
If width/height are omitted, some browsers may render the SVG at a default size (e.g., 300x150 pixels, similar to <img> fallback behavior), which might not match your design intent. Explicitly setting width/height ensures the SVG is visible and avoids unexpected scaling.
-
Legacy Browser Support:
Older browsers (pre-2010s) sometimes ignored the viewBox attribute unless width/height were explicitly defined, leading to rendering issues.
2. Why Absolute Pixels Are Problematic
-
Responsive Design:
Fixed pixels (px) do not adapt to different screen sizes or container dimensions, leading to poor user experiences on mobile or dynamically resized layouts.
-
Accessibility:
Overriding default browser scaling with fixed dimensions can harm accessibility for users who adjust default font/text sizes.
3. Modern Best Practices for SVG
To balance reliable rendering with responsiveness:
a. Always Use viewBox
<svg viewBox="0 0 100 100" ...>
- The
viewBox defines the coordinate system and aspect ratio, enabling proportional scaling.
b. Set width/height Using Relative Units or CSS
c. Fallback for Older Browsers
If supporting legacy browsers, include width/height attributes with viewBox:
<svg width="200" height="200" viewBox="0 0 100 100">
The viewBox ensures proportional scaling even if width/height are fixed.
4. When Are Pixels Acceptable?
- Static, Non-Responsive Use Cases:
If the SVG is part of a fixed-size graphic (e.g., a logo in a header with a known width), pixels are fine.
- Inline SVG in Email Clients:
Some email clients (e.g., Outlook) require fixed dimensions for SVG rendering.
5. Key Takeaway
Specifying pixels is not inherently "frowned upon"—it’s about using the right approach for the context:
- Use
viewBox + relative units/CSS for responsiveness.
- Use pixels only when fixed dimensions are explicitly required.
This balances compatibility, accessibility, and modern design principles.