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
<!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>
/* 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:
How does the SVG Viewbox & Viewport work in CSS ?
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
Contact Us