Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • CSS Tutorial
  • CSS Exercises
  • CSS Interview Questions
  • CSS Selectors
  • CSS Properties
  • CSS Functions
  • CSS Examples
  • CSS Cheat Sheet
  • CSS Templates
  • CSS Frameworks
  • Bootstrap
  • Tailwind
  • CSS Formatter
Open In App
Next Article:
How does CSS work under the hood ?
Next article icon

How does the SVG Viewbox & Viewport work in CSS ?

Last Updated : 04 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

SVG (Scalable Vector Graphics) is a format used to create graphics on the web that can scale without losing quality. Within SVG, two important concepts are the viewBox and viewPort, which play crucial roles in how SVG elements are displayed and scaled.

Table of Content

  • What is SVG ViewBox?
  • What is SVG ViewPort?
  • How Do They Work Together?
  • Employing External SVG with viewbox and viewport Attributes:
  • Integrating SVG via CSS Background with viewBox and viewport Attributes:
  • Difference

What is SVG ViewBox?

The viewBox attribute in SVG defines the coordinate system and the dimensions of the "viewable" area within an SVG element. It specifies the position and dimensions of the SVG content relative to the SVG canvas. For example, a viewBox of "0 0 100 100" means that the SVG content covers an area from (0, 0) to (100, 100) units.

What is SVG ViewPort?

The viewPort (or viewport) refers to the area where an SVG image is displayed on the screen or within an HTML document. It is the visible area that contains the SVG content. The width and height attributes of the SVG element determine the size of the viewport.

How Do They Work Together?

  • The viewBox defines the coordinate system and content area.
  • The width and height attributes of the SVG element define the viewport size.
  • When the viewBox and viewport have different aspect ratios, the SVG content is scaled to fit the viewport while maintaining its proportions.
  • If the aspect ratios match, the SVG content is displayed without distortion.

Example: Illustration of Inline SVG with viewbox and viewport Attributes

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport"            content="width=device-width, initial-scale=1.0">     <title>Inline SVG Example</title>     <style>         body {             font-family: Arial, sans-serif;             background-color: #f7f7f7;         }          .container {             width: 80%;             margin: 0 auto;             text-align: center;             padding-top: 50px;         }          .svg-container {             width: 100px;             height: 100px;             display: inline-block;             margin-top: 20px;         }     </style> </head>  <body>     <div class="container">         <h1>Inline SVG Example</h1>         <div class="svg-container">             <svg viewBox="0 0 100 100"                   width="100" height="100"                   preserveAspectRatio="xMidYMid meet">                 <circle cx="50" cy="50" r="40" fill="blue" />             </svg>         </div>     </div> </body>  </html> 

Output:

Screenshot-2024-03-28-165931

Employing External SVG with viewbox and viewport Attributes

In this method, we put the SVG picture in a separate file and then add it to our webpage using a special tag called <object>. The viewbox helps us to define the size and shape of the picture, and the viewport attributes width and height help us to control the size of the SVG within its containing element. preserveAspectRatio ensures that the SVG maintains its aspect ratio.

Syntax:

<object type="image/svg+xml" data="path/to/svg" width="value" 
height="value" style="preserveAspectRatio: value;">
</object>

In this syntax:

  • type="image/svg+xml" specifies that the object contains an SVG image.
  • data="path/to/svg" points to the external SVG file.
  • width="value" and height="value" control the dimensions of the SVG within the object.

Example: Illustration of Employing External SVG with viewbox and viewport Attributes

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport"            content="width=device-width, initial-scale=1.0">     <title>           External SVG with viewbox            and viewport Attributes       </title>     <style>         body {             display: flex;             justify-content: center;             align-items: center;             height: 100vh;             margin: 0;         }          .container {             text-align: center;         }          svg {             display: block;             margin: 0 auto;         }     </style> </head>  <body>     <div class="container">         <h1>               External SVG with viewbox                and viewport Attributes           </h1>         <!-- External SVG embedded with specified               viewBox and viewport attributes -->         <svg xmlns="http://www.w3.org/2000/svg"               viewBox="0 0 100 100" width="300" height="200"              style="border:1px solid black;">             <circle cx="50" cy="50" r="40" stroke="black"                      stroke-width="3" fill="red" />         </svg>     </div> </body>  </html> 

Output:

Screenshot-2024-03-28-170655

Integrating SVG via CSS Background with viewBox and viewport Attributes:

In this method we use SVG as a background image in CSS. The viewbox helps us to define the size and shape of the picture, and the viewport attributes width and height help us to control the size of the SVG within its containing element. preserveAspectRatio ensures that the SVG maintains its aspect ratio. The background-size property controls how the SVG scales within its container.

Syntax for HTML:

<div class="svg-background"></div>

Syntax for CSS:

.svg-background {
background-image: url('path/to/svg');
background-size: value;
}

Example: Illustration of Integrating SVG via CSS Background with viewBox and viewport Attributes

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport"            content="width=device-width, initial-scale=1.0">     <title>           Integrating SVG            via CSS Background       </title>     <link rel="stylesheet"            href="style.css"> </head>  <body>     <div class="container">         <div class="content">             <h1>                   Integrating SVG                    via CSS Background               </h1>         </div>     </div> </body>  </html> 
CSS
/* style.css */  body {     margin: 0;     font-family: Arial, sans-serif;     background-color: #f4f4f4;     display: flex;     justify-content: center;     align-items: center;     height: 100vh; }  .container {     width: 300px;     height: 300px;     background-image: url( 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /></svg>');     background-size: cover;     background-repeat: no-repeat;     border: 1px solid black;     border-radius: 10px;     box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);     overflow: hidden;     display: flex;     justify-content: center;     align-items: center; }  .content {     text-align: center;     color: black; }  h1 {     font-size: 20px;     margin-bottom: 10px; }  p {     font-size: 8px;     line-height: 1; } 

Output:

Screenshot-2024-03-27-143344

Difference between SVG Viewbox & Viewport

AspectSVG ViewBoxSVG ViewPort
DefinitionDefines the coordinate system and content area within the SVG.Defines the visible area where the SVG content is displayed.
AttributeDefined within the SVG content using the viewBox attribute.Defined by the width and height attributes of the SVG element.
PurposeSpecifies the position and dimensions of the SVG content relative to the SVG canvas.Determines the size of the visible area that contains the SVG content.
Aspect RatioCan have different aspect ratios from the viewport.Usually matches the aspect ratio of the viewport.
Scaling BehaviorDetermines how SVG content scales and fits within the viewport.Affects how the SVG image is displayed in terms of size and proportions.

Next Article
How does CSS work under the hood ?

V

virat555
Improve
Article Tags :
  • Web Technologies
  • CSS
  • CSS-Questions

Similar Reads

  • How to Set Viewport Height & Width in CSS ?
    Set viewport height and width in CSS is essential for creating responsive and visually appealing web designs. We'll explore the concepts of setting viewport height and width by using various methods like CSS Units, Viewport-Relative Units, and keyframe Media Queries. Table of Content Setting viewpor
    3 min read
  • How does CSS work under the hood ?
    Cascading Style Sheets referred to as CSS, is a stylesheet language used to design and describe the presentation of the webpage to make it attractive. The main use of CSS is to simplify the process of making web pages presentable. The way elements should be rendered on screen is described by CSS. CS
    3 min read
  • How to Work with Fill & Stroke Color in CSS ?
    Fill color is the interior color of an element and the Stroke Color is the color that is applied to the outline of the element. we will work with this fill and stroke color in CSS on various SVG shapes. These are the following approaches: Table of Content Using Different Fill and Stroke Colors on SV
    3 min read
  • New CSS Viewport Units (vi, vb, vmax, vmin)
    The original viewport units, such as vw (viewport width) and vh (viewport height), have been widely used to create responsive layouts that adapt to different screen sizes. Using the vh unit on mobile is buggy because the viewport size won’t include the browser’s address bar UI. However, the newly in
    3 min read
  • What are the real world usage of CSS with SVG ?
    SVG stands for Scalable Vector Graphics. It is an image format like HTML for designing 2D graphics. Vector images are different from raster images, raster images are those having .png, .jpeg format uses a grid of tiny pixels to create an image and as you zoom in on the image the pixels of the image
    3 min read
  • How to set the perspective from where an element is viewed in CSS ?
    In this article we will see, how the CSS perspective works. The CSS perspective is a new CSS property that has to provide to manage the distance between the z-axis. We all know that we work with a 2D surface. So if we rotate our objects, then this completeness is not displayed. The solution to this
    2 min read
  • CSS Peeper - New tool for Web Designers
    CSS Peeper is a browser extension that is a CSS viewer and is tailored for Designers. Using this designers can focus on design, and spend as little time as possible digging in code. What’s the line height, button, or font size on a website? All these questions get answered using CSS peeper. It enabl
    4 min read
  • How to change svg icon colors with Tailwind CSS ?
    SVG stands for Scalable Vector Graphics and is an XML-based ( can be edited ) vector image format. SVG is commonly used for icons, animations, interactive charts, graphs, and other dynamic graphics in the browser. As it is XML-based, you can easily edit or change the SVG icon colors with Tailwind. A
    3 min read
  • How to resize SVG icon using Tailwind CSS ?
    SVG stands for Scalable Vector Graphics and is an XML-based ( can be edited ) vector image format. SVG is commonly used for icons, animations, interactive charts, graphs, and other dynamic graphics in the browser. As it is XML-based, you can easily resize the SVG icon using Tailwind. Approach: You c
    3 min read
  • How CSS Positioning and Flexbox Work?
    CSS positioning and Flexbox are fundamental tools for web layout and design. Understanding how they work can help you create more responsive and well-structured web pages. CSS positioning allows you to control the placement of elements on the web page. There are several positioning schemes in CSS. T
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences