- Practical SVG
- This article is authorized by the original author Chris Coyier
- The Nuggets translation Project
- Translator: MAYDAY1993
- Proofreader: Zhouzihanntu Hpoenixf
Maybe you want to control the size of any images you post online, hey! Is you! Logo ! You should be this size:
<img src="logo.png" class="logo" />Copy the code
.logo {
width: 220px;
height: 80px;
}Copy the code
The following to continue
The image should also be controllable in size.
But if the element you are scaling happens to be SVG, the result may not be what you expected. Defining the dimensions of SVG is a bit more complicated than defining img. I’m not trying to scare you. Complexity is not a bad thing because it gives you more control and opens up some interesting possibilities.
When it comes to sizing SVG images, keep these two concepts in mind:
- A viewport is the height and width of an element: the size of the visible area of an SVG image. This is often done directly in SVG or via CSSwidth 和 heightProperties.
viewBox
是svg
To determine the coordinate system and aspect ratio. Four values arex.y.width, andheight.
We usually do this:
<svg width="100" height="100" viewBox="0 0 100 100">
<! -- alternatively: viewBox="0, 0 100, 100" -->Copy the code
In this case, the size of the view is exactly the same as the viewBox (Fig 6.1). SVG will be displayed in the place it occupies visually. CodePen Embed
Fig.6.1: ViewPort and viewBox are exactly the same. This happens if you do not set the length or width of the SVG (neither properties nor CSS), or if you set the length and width, they are consistent with the aspect ratio of the viewBox.
Now we double the width and height, like this:
<svg width="200" height="200" viewBox="0 0 100 100">Copy the code
Will SVG occupy a 100 by 100 area in the upper left corner of a 200 by 200 element? No, everything in SVG will be enlarged in the new larger space (Fig 6.2). CodePen Embed
Fig.6.2: The ViewPort becomes larger while the viewBox remains the same, and the picture is enlarged to fit the viewport.
The aspect ratios of the squares still match. This is why it is useless to think of values anywhere in SVG as pixels, because they are not pixels; They’re just numbers in an arbitrary coordinate system.
So, what if aspect ratios don’t match?
<svg width="300" height="75" viewBox="0 0 100 100">Copy the code
By default, SVG displays itself as large as possible, centered along the longest size (Fig 6.3). CodePen Embed
Fig 6.3: The Viewport is larger, but no longer matches the aspect ratio of the viewBox. So by default, images are shown as large as possible without cropping, and are centered in the direction of large proportions.
If you want to regain control of this behavior, the SVG element has an attribute that takes effect!
preserveAspectRatio
Like this:
<svg preserveAspectRatio="xMaxYMax">Copy the code
The x and Y parts of this value are followed by Min, Mid, or Max. SVG is usually centered in views because there is a default xMidYMid value. If you change the value to xMaxYMax, this tells SVG to be as far to the right as possible horizontally and as far to the bottom as possible vertically. Then make it as big as possible without cutting.
The “No tailoring” section is another aspect of the preserveAspectRatio. The default value is xMidYMid meet – note the “meet”. You can use slice instead of meet. This means to fill an area completely; Tailoring is also ok.
The combination of meet and meet has nine possible aligned values (Fig. 6.4).
Figure 6.4: Example of a preserveAspectRatio with meet value.
The slice combination also has nine possible aligned values (Fig. 6.5).
Fig 6.5: Examples of preserveAspectRatio with slice values.
To test this idea I made a test tool. Sara Soueidan has also written an in-depth article on this topic, and she does a good job of exploring the relevance of this idea to CSS. The background-size attribute has two values: contain and cover. Contain value is used to “make sure the whole image is still visible even if the screen is small”, as in meet. The cover value “ensures that the image covers the entire background area, even if some parts of the image may be clipped,” as in slice.
Even the aligned section has a corresponding CSS property: background-Position. The default background-position value is 0, 0, which means “top left”. Just like xMinYMin. If you change it to 50% 100%, it’s like xMidYMax!
Fig. 6.6 These examples make the connection clearer.
PreserveAspectRatio Value and CSS properties
preserveAspectRatio= "xMinYmax meet" |
preserveAspectRatio= "xMidYMid meet" |
preserveAspectRatio= "xMinYmax slice" |
preserveAspectRatio= "xMidYMid slice" |
Figure 6.6: Values of preserveAspectRatio and similar CSS properties
Remember: they are not universal in code; It’s just conceptually relevant.
What if you don’t want to worry about aspect ratios and have SVG scale with view size, just like raster images? Set the preserveAspectRatio property to ‘None’ (Fig 6.7)!
<svg preserveAspectRatio="none" viewBox="0 0 100 100">Copy the code
CodePen Embed
Figure 6.7: Example of preserveAspectRatio=” None”
Amelia Bellamy-Royds has written a comprehensive article on scaling SVG, in which she describes how SVG can actually contain other SVGS with different aspect ratios and behaviors, so you can have one diagram partially scaled and the rest of it displayed normally; This is cool and unique for SVG.
Method of drawing board size scaling
When you draw SVG in your editing software, the software may provide you with some kind of artboard to draw on. This is not a technical SVG term; It’s actually a visual metaphor for the viewBox.
Suppose you’re designing a set of ICONS for a website. One way is to have all the artboards touch each edge of the icon (Fig 6.8).
Figure 6.8: Examples of images touching edges in Adobe Illustrator.
Here’s a quick tip to crop artboards in Illustrator: Select the Artboard Tool, then select “Fit to Artwork Bounds” from the Presets menu (Fig 6.9).
Fig 6.9: Menu options in Adobe Illustrator allow you to resize your artboard based on the edges of your image.
The advantage of this technique is alignment (Fig.6.10). If you want to align either side of these ICONS with anything else, it’s easy to do. There is no magic you need to deal with or positioning patterns that need to be constantly tweaked.
.icon.nudge {
position: relative;
right: -2px; /* UGHCKKADKDKJ */
}Copy the code
Fig 6.10: ICONS are seamlessly spaced and edge aligned.
The disadvantage of this cutting technique is the relative size. Imagine you take a general approach to defining the width and height of an icon, like this:
.icon {
width: 1em;
height: 1em;
}Copy the code
A tall, slender icon will shrink to fit that area and may appear small. Or you might be trying to intentionally use a small star shape as an icon, expecting the star to have a square aspect ratio and therefore zoom in to fill the area, but the result is bigger than you want.
Here is an example of two ICONS that are square in size (Fig 6.11). The “expand” icon looks normal because it has a square aspect ratio to adjust. But the “Zap it” icon has a high, narrow aspect ratio, so it looks small and floats on the same square area.
Fig 6.11: Two ICONS in a button are the same size square area. The one on the top responds well, but the one on the bottom floats strangely in the region.
Another method is to create a uniform size palette (Fig 6.12) :
Figure 6.12: An example of the same size drawing in Illustrator.
The advantages and disadvantages are exactly reversible. You may encounter alignment issues because not all icon edges touch viewBox edges, which can be frustrating and may sometimes need to be adjusted (Fig.6.13).
Fig 6.13: You can adjust the relative size of the ICONS, but that will make alignment more difficult.
But you don’t have a relative size problem, because the viewBox is the same for all artboards. If any icon looks too big or too small, you can adjust the palette to fit the sequence.
Now that we know about dimensions, it’s time to look at how SVG fits into the elastic world of responsive design.
Reactive SVG
A hallmark of responsive design is streaming layout. Content – including images – is designed to fit both its container and its screen. If responsive design is new to you, Ethan Marcotte’s important article on the subject in 2010 is a good place to start learning about responsive design. SVG works well with responsive design.
- Responsive design is elastic. SVG is! It works well in every size. Responsive design is a philosophy that focuses on how a website is presented and rendered in any browser. Relatively small SVG files and performance-first policies like an SVG icon system are part of responsive design.
But perhaps the most significant connection between SVG and responsive design is the possibility of querying CSS media. Media queries use CSS to move, hide, or show elements based on factors such as the height or width of the browser window. These elements can be anything: sidebars, navigation bars, ads, anything you have. It could also be an SVG element.
Imagine an icon that shows different levels of detail based on the amount of space available. That’s when Joe Harrison designed a really simpleDemo designed with famous ICONSWhat comes to mind, (Fig 6.14).
Fig 6.14: Joe Harrison’s demo of Disney ICONS in different sizes.
On websites, we often replace images with other images. What’s interesting here is that we’re not replacing the image; They’re all the same picture. Or at least they could be the same one. The signature “D” is the same “D” used in the most complex version of the diagram.
Common notation in CSS.
We organize SVG like this:
<svg class="disney-logo">
<g class="magic-castle">
<! -- paths, etc -->
</g>
<g class="walt">
<! -- paths, etc -->
</g>
<g class="disney">
<path class="d" />
<! -- paths, etc -->
</g>
</svg>Copy the code
This is easy to do in Illustrator, by the way (Fig 6.15). Here you write components and names that become ids when exported in SVG, and you can use these ids to define styles. However, I personally prefer to use classes because they are not unique (so you don’t suddenly have multiple ids of the same value on a page) and classes have a lower and more manageable CSS specificity weight. In a code editor, it’s very easy to turn an ID into a class using a look-and-replace operation.
Fig 6.15: Named layers and shapes in Adobe Illustrator.
The corresponding CSS looks like this:
@media (max-width: 1000px) {
.magic-castle {
display: none;
}
}
@media (max-width: 800px) {
.walt {
display: none;
}
}
@media (max-width: 600px) {
.disney > *:not(.d) {
display: none;
}
}Copy the code
Note that there is an artificial example of hiding part of the image at different breakpoints, but that is what you will do, and there may be some resizing. Everything you can do with CSS is listed here. Some animations may be appropriate at certain breakpoints, but not at others. Maybe. Maybe you change some of the fill colors to simplify the adjacent shapes.
Things will be more interesting! Depending on how SVG is used, these media queries may actually be different. SVG used as IMG, iframe, or Object has its own view. This means that embedded CSS responds to media queries on this basis, rather than the entire browser window view. This means that you declare image-based media queries based on the width of the image, not the width of the entire page.
This is a very attractive idea: an element arranges itself based on its own attributes, not the page. Am I this wide? right Am I this tall? Too. That way, SVG responds to the situation it is in, not to any document it is in.
As I wrote, this is called “element query” in CSS, but it doesn’t actually exist in normal HTML/CSS. Once again, SVG is ahead of its time.
Let’s look at the animation
Speaking of what SVG does well, let’s move on to animation. Everything we have relied on so far is ready for us. Hold on tight!
The only constant has changed: a q&A with Ethan Marcotte
The framework
In this excerpt, Ethan Marcotte examines frameworks to think about the rules of responsive design and apply them to our work.