Author: Ahmad Shadeed Translator: Front-end Xiaozhi Source: Developers
Like it and see. Make it a habit
In this paper,
GitHub
Github.com/qq449245884…Has included more categories of previous articles, as well as a lot of my documentation and tutorial material. Welcome Star and Perfect, you can refer to the examination points for review in the interview, I hope we can have something together.
One decision that front-end developers need to make when building a website is the way images are introduced. It can be a tag, or it can be a CSS background property, or it can use SVG . Choosing the right approach is important, and it can have a big impact on performance and accessibility.
In this article, we’ll learn the various ways to introduce images, the advantages and disadvantages of each, and when and why to use them.
HTML <img>
The element
In the simplest case, the img element must contain the SRC attribute:
<img src="cool.jpg" alt="">
Copy the code
Set the width and height properties
As the page loads, they make some layout changes as the page image loads. To avoid this, we can set width and height properties for it:
<img src="cool.jpg" width="200" height="100" alt="">
Copy the code
While this may seem too simple for some people, it works. Let’s use a legend to clarify this concept:
We see that the image on the right retains space even though it’s not loaded, right? That’s because the width and height are set.
Hide images with CSS
Images can be hidden with CSS. However, it will still be loaded in the page. Therefore, be careful when performing this operation. If an image should be hidden, it may be for decorative purposes.
img {
display: none;
}
Copy the code
Again, the above method does not prevent the browser from loading the image, even if it is visually hidden. The reason is that is considered a replaced element, so we have no control over what it loads.
Everyone said there was no project on your resume, so I found one and gave it away【 Construction tutorial 】.
Accessibility issues
Access to HTML images by setting the Alt attribute to a meaningful description is very helpful for screen reader users.
However, if an Alt description is not needed, please do not remove it, if you do, the image SRC will be read out, which is very bad for accessibility.
Not only that, if the image doesn’t load for some reason, and it has a clear Alt, it will be displayed as a fallback. Again, I’m going to illustrate this with a legend.
Suppose we have the following picture:
<img class="food-thumb" width="300" height="200" src="cheescake.jpg">
<img class="food-thumb" width="300" height="200" src="cheescake.jpg" alt="">
Copy the code
When SRC is invalid and the image is not loaded. The first one has no Alt attribute, and the second one has an empty Alt attribute. Here’s what they look like:
Images without Alt still retain their space, which is confusing and not conducive to access. The other image, with Alt empty, will fold up to look like a dot, because it has a border.
However, when the Alt attribute has a value, it looks like this:
Isn’t that good feedback? In addition, you can add pseudo-elements to image sources when they fail.
Responsive image
The advantage of is that it can be expanded to have multiple versions of a photo for a particular viewport size. We have two different ways to generate a set of responsive images:
1. Srcset properties
<img src="small.jpg" srcset="medium.jpg 500w, large.jpg 800w" alt="">
Copy the code
That’s easy. For me, srCSet can display multiple image sizes depending on the screen width, which is not a perfect solution. It lets the browser choose the right image, and there’s nothing we can do about it.
2. The picture TAB
<picture>
<source srcset="large.jpg" media="(min-width: 800px)" />
<source srcset="medium.jpg" media="(min-width: 500px)" />
<img src="small.jpg" />
</picture>
Copy the code
Another option is to use the
Codepen. IO /shadeed/pen…
Resize the image
For , we also have a nice set of features object-fit and object-position available. They control the size and positioning of , just like CSS background images.
The object-fit values are: fill, contain, cover, none, scale-down. Such as:
img {
object-fit: cover;
object-position: 50% 50%;
}
Copy the code
CSS Background image
When a CSS background is used to display an image, it requires an element with content or a specific width or height. In general, the main use of background images should be for decorative purposes.
How to use CSS background images
First, we need an element
// html
<div class="element">Some content</div>
// css
.element {
background: url('cool.jpg');
}
Copy the code
Multiple background
The advantage of using CSS background images is that you can set multiple backgrounds. Consider the following example:
.element {
background: url('cool-1.jpg'), url('cool-2.jpg');
}
Copy the code
Hidden image
We can hide and display images in a particular viewport, and if we don’t use CSS to set up the image, it won’t be downloaded. This is an added benefit compared to using < IMG >.
In the example above, we have a background image that is displayed only when the viewport width is greater than 700px.
Accessibility issues
If not used properly, background images can affect accessibility. For example, use it for your article topic, which is critical to your article.
#### cannot be downloaded by non-developers
The average person knows that if you want to save an image, just click the left mouse button and select Save. This is not the case with CSS background images, we must first examine the element and then open the link in the URL in DevTools before we can download the images added with CSS.
Pseudo elements
Pseudo-elements can be used with A CSS background image, for example to display an overlay image at the top of the image. For this is not possible until we add a separate element to the overlay.
SVG <Image>
SVG is considered to be an image whose greatest power is to scale without compromising quality. Additionally, with SVG, we can embed JPG, PNG, or SVG images. See HTML below:
<svg width="200" height="200">
<image href="cheesecake.jpg" height="100%" width="100%" preserveAspectRatio="xMidYMid slice" />
</svg>
Copy the code
Have you noticedprepareAspectRatio
? What it does is allow images to take up the entire width and height of SVG without being stretched or compressed.
When the width is large, it fills its parent (SVG) width without stretching.
This is very similar to object-fit: cover or background-size: cover in CSS.
Accessibility issues
Regarding accessibility of SVG, this reminds me of the
<svg width="200" height="200">
<title>A photo of blueberry Cheescake</title>
<image href="cheesecake.jpg" height="100%" width="100%" preserveAspectRatio="xMidYMid slice" />
</svg>
Copy the code
We can also use the
element
<svg width="200" height="200">
<title>A photo of blueberry Cheescake</title>
<desc>A meaningful description about the image</desc>
<image href="cheesecake.jpg" height="100%" width="100%" preserveAspectRatio="xMidYMid slice" />
</svg>
Copy the code
Non-developers cannot download it
You must check the element and copy the URL of the image before you can download an image embedded in SVG. However, if we want to prevent users from downloading specific images, this can be a good thing.
Use cases
Hero Section
When building the Hero section, sometimes we need an image below the title and other content. See below:
Some requirements:
- Background images can be replaced dynamically
- The picture has an overlay to make it easier to read
- Images come in three sizes: small, medium and large. Each one is targeted at a specific viewport.
Before starting the solution, let’s ask ourselves about the nature of this context. Here are some introductory questions:
- Is it important to keep this image for the user, or can you skip it?
- Do we need to use it on all viewport sizes?
- Is it static or dynamically changing?
Solution 1
By using multiple CSS backgrounds, we can use one as a overlay and the other as the actual image. Look at the CSS below:
.hero {background-image: linear-gradient(rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.4)), var('landscape.jpg');
background-repeat: no-repeat;
background-size: 100%, cover;
}
Copy the code
While this solution works, you can change the background image dynamically using JavaScript. See below:
<section class="hero" style="Background: Linear-gradient (Rgba (0, 0, 0, 0.5), Rgba (0, 0, 0, 0.5)), URL ('landscape.jpg');> <! -- Hero content --> </section>Copy the code
An inline style is added here. While this is doable, it looks ugly and is not practical.
Maybe we could use CSS variables? Let’s explore.
<section class="hero" style="--bg-url: url('landscape.jpg')"> <! -- Hero content --> </section>Copy the code
Now, we can easily update the — bg-URL variable to dynamically change the back, which is a million times better than the inline stuff.
Summary:
- This scheme only works if the picture is unimportant
- This scheme is only suitable for some static sites, because no images are pulled from the background
Codepen. IO /shadeed/pen…
Everyone said there was no project on your resume, so I found one and gave it away【 Construction tutorial 】.
Solution 2
The scheme can be used with an IMG tag:
<section class="hero">
<h2 class="hero__title">Using Images in CSS</h2>
<p class="hero__desc">An article about which and when to use</p>
<img src="landscape.jpg" alt="">
</section>
Copy the code
In CSS, we need to position the image absolutely below the content, and we also need to use pseudo-elements as overlay layers.
.hero {
position: relative;
}
.hero img {
position: absolute;
left: 0;
top: 0;
z-index: -1;
width: 100%;
height: 100%;
object-fit: cover;
}
.hero:after {
content: ""; position: absolute; left: 0; top: 0; z-index: -1; width: 100%; height: 100%; Background: Rgba (0, 0, 0, 0.4); }Copy the code
The advantage of this solution is that you can easily change the SRC attribute of the image. Also, images are more useful if they are important.
Another feature I like using with HTML is the ability to add fallbacks without loading images. The fallback at least keeps the content readable.
.hero img {
/* Other styles */
background: #2962ff;
}
Copy the code
Background color is a substitute aspect when the image source path is not correct.
Codepen. IO /shadeed/pen…
The website Logo
A website Logo is important because it distinguishes the website from other websites. To embed the logo, we have a few options:
*<img>
-> png,jpg, orsvg
- Inline SVG
- background
Next, let’s see which approach is more appropriate.
Logo with lots of details
When a logo has many details or shapes, it may not be beneficial to use it as an embedded SVG. I recommend using and the image type can be PNG, JPG or SVG.
A simple Logo that requires animation
We have a simple logo that contains shapes and text. When hovering, shapes and text need to change color. How to do? The best solution for me is to use embedded SVG.
HTML
<a href="#">
<svg class="logo" width="115" height="47" xmlns="http://www.w3.org/2000/svg">
<g transform="translate(-5 -5)" fill="none" fill-rule="evenodd">
<rect fill="#D8D8D8" transform="Rotate 45 (28.5 28.5)" x="9" y="9" width="39" height="39" rx="11" />
<text font-family="Rubik-Medium, Rubik" font-size="25" font-weight="400" fill="#6F6F6F">
<tspan x="63.923" y="36.923">Rect</tspan>
</text>
</g>
</svg>
</a>
Copy the code
CSS
.logo rect,. Logo text {transition: 0.3s ease-out; } .logo:hover rect, .logo:hover text { fill:#4a7def;
}
Copy the code
Codepen. IO /shadeed/pen…
In response to the Logo
This reminds me of Smashing Magazine’s logo. I love how it goes from a small icon to a complete logo. See the following model:
The perfect solution is to use the
<a class="logo" href="/">
<picture>
<source media="(min-width: 1350px)" srcset="sm-logo--full.svg"><img src="sm-logo.svg" alt="Smashing Magazine"></picture>
</a>
Copy the code
In the CSS, we need to change the viewport width to equal to or greater than 1350px.
.logo { display: inline-block; width: 45px; } @media (min-width: 1350px) { .logo { width: 180px; }}Copy the code
This is the simple and straightforward solution.
Codepen. IO /shadeed/pen…
Logo with gradient
When logos have gradients, the process of exporting them from design applications such as Illustrator or Sketch can be imperfect and sometimes interrupted.
Using SVG, we can easily add gradients to logos. I added
<svg class="logo" width="115" height="47" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="gradient" x1="0%" y1="100%" x2="0%" y2="0%">
<stop offset="0%" stop-color="#4a7def"></stop>
<stop offset="50%" stop-color="#ab4787"></stop>
</linearGradient>
</defs>
<g transform="translate(-5 -5)" fill="none" fill-rule="evenodd">
<rect fill="#AB4787" transform="Rotate 45 (28.5 28.5)" x="9" y="9" width="39" height="39" rx="11" />
<text font-family="Rubik-Medium, Rubik" font-size="30" font-weight="400" fill="url(#gradient)">
<tspan x="63.923" y="36.923">Rect</tspan>
</text>
</g>
</svg>
Copy the code
Codepen. IO /shadeed/pen…
The avatars
For user avatars, there are many shapes, but the most common ones are rectangles or circles. In this use case, an important technique is introduced that will be useful to you.
First, let’s look at the following model. Please note that we have a perfect avatar and are 100% clear.
However, this design is not so good when users upload half-white avatars or very light avatars.
Note that in the model above, it is not clear that there is a circle in it unless you really focus. That’s a problem. To solve this problem, we should add a border inside the avatar in case the image is too bright to clear.
We have several options
<img>
The element<img>
和<div>
The element<div>
With CSS background- SVG
<image>
Which is the best? Let’s explore.
Use HTML<img>
The first thing you might think of is adding a border, right? Let’s explore this question.
.avatar {
border: 2px solid #f2f2f2;
}
Copy the code
Our goal is to blend the internal border with the image, which is not very practical.
use<img>
和 <div>
The element
The problem now is that to add an internal border, we can’t use box-shadow because it doesn’t work on the image. The solution wraps the avatar with
HTML
<div class="avatar-wrapper">
<img class="avatar" src="shadeed2.jpg" alt="A photo of Ahmad Shadeed">
<div class="avatar-border"></div>
</div>
Copy the code
CSS
.avatar-wrapper {
position: relative;
width: 150px;
height: 150px;
}
.avatar-border {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
border-radius: 50%;
border: 2px solid rgba(0, 0, 0, 0.1);
}
Copy the code
By using a border with 10% opacity black on
IO /shadeed/pen…
use<div>
With CSS background
If I use
HTML
<div class="avatar" style="--img-url: url(shadeed2.jpg)"></div>
Copy the code
CSS
.avatar {
background: var(--img-url) center/cover;
width: 150px;
height: 150px;
border-radius: 50%;
box-shadow: inset 0 0 0 2px rgba(# 000, 0.1);
}
Copy the code
IO /shadeed/pen…
Using SVG<image>
To me, this is the most interesting solution. I noticed it while checking out Facebook’s new design.
<svg role="none" style="height: 36px; width: 36px;">
<mask id="avatar">
<circle cx="18" cy="18" fill="white" r="18"></circle>
</mask>
<g mask="url(#avatar)">
<image x="0" y="0" height="100%" preserveAspectRatio="xMidYMid slice" width="100%" xlink:href="avatar.jpg" style="height: 36px; width: 36px;"></image>
<circle cx="18" cy="18" r="18"></circle>
</g>
</svg>
Copy the code
First of all, it contains the following contents:
- Mask used to cut images into circles
- A group to which a mask has been applied
image
Itself withPreserveAspectRatio = "xMidYMid"
- A circle used for an inner boundary
circle { stroke-width: 2; Rgba (0, 0, 0, 0.1); fill: none; }Copy the code
IO /shadeed/pen…
Original text: developers.google.com/web/fundame…
The bugs that may exist after code deployment cannot be known in real time. In order to solve these bugs, I spent a lot of time on log debugging. Incidentally, I recommend a good BUG monitoring tool for youFundebug.
communication
This article is updated every week, you can search wechat “big move the world” for the first time to read and urge more (one or two earlier than the blog hey), this article GitHub github.com/qq449245884… It has been included and sorted out a lot of my documents. Welcome Star and perfect. You can refer to the examination points for review in the interview.