Severin Spörri
Severin Spörri

Reputation: 120

How can I use a Javascript variable to define the width of an SVG element?

I wanted a red square in the middle of my (landscape-format) screen. But now the side length of the square appears to be the screen width anyway. How do I set it to the variable square_side?

    <!DOCTYPE html>
        <html lang="en">
        <body>
        <script>
        const square_side = Math.min(screen.availWidth, screen.availHeight);
        </script>
        <div style=" display: flex; justify-content: center; align-items: center;">
        <svg width=square_side viewBox="0 0 100 100">
        <polygon fill=red
        points="0,0 0,100 100,100 100,0" />
    
        </svg>
        </div>
        </body>
        </html>

Upvotes: 0

Views: 153

Answers (1)

Medet Tleukabiluly
Medet Tleukabiluly

Reputation: 11950

<!DOCTYPE html>
<html lang="en">

<body>
  <div style=" display: flex; justify-content: center; align-items: center;">
    <svg viewBox="0 0 100 100">
        <polygon fill=red
        points="0,0 0,100 100,100 100,0" />
    
        </svg>
  </div>
  <script>
    document.querySelector('svg').setAttribute('width', Math.min(screen.availWidth, screen.availHeight))
  </script>
</body>

</html>

Upvotes: 1

Related Questions