Mario Hernandez: Responsive image styles

In a nutshell, responsive image styles are a collection of image styles. It can be confusing because the similarities in their names, but responsive image styles are a bundle that holds one or more image styles.

What's the use of responsive image styles?

If you read the posts about the <picture> element as well as the one about srcset and sizes attributes, we discussed that whether you are doing art direction or resolution switching, we need to provide the browser with a collection of images to serve to different devices. In Drupal the way we provide the collection of images is by using responsive image styles.

Image removed.

Naming responsive image styles

In the previous post we went in detail about best practices for naming image styles. Properly naming responsive image styles is just as important but there are some differences in guidelines. While naming image styles is mostly based on the characteristics of the images (aspec ratio, orientation, dimensions), naming responsive image styles is typically based on their use case. Let's take a look at some examples.

Let's say we are building a photo gallery where we will use a series of images to display as a slider or photos grid. We may not be as concerned about the images aspect ratio or dimentions because we already have image styles in place to handle that. We're only interested on how the images will be used. In this example the use case is a Gallery. So a name for the responsive image style that makes sense to me would be Gallery or Photo gallery. Another example would be creating a responsive image style for your website's hero component. Regardless of what the images dimensions are, the responsive image style can be called Hero. Both of these examples are for very unique use cases, but there are also cases for more common type of responsive images styles such as a listing of news articles or events, a featured news article or a page for team member photos. In these cases, we can use names that we can reuse elsewhere. Something like Person listing, News full, Content grid, or 16:9 (Max 460px).

Back to hands-on exercises

We are going to create a new responsive image style in which we will make use of the image styles we created in the previous post. Let's pretend the images we are targeting will be used for displaying News and Events listings (Similar to this, and example below).

Image removed.

Most websites use patterns that they repeat across their sections or pages. The news listing example above is a pattern that can be used for not only displying news articles, but maybe also events, social media posts, and more. This is great because identifying these patterns can help us create better image styles and responsive image styles that are reusable. This is what I meant in the previous post when I said that if you are fortunate enough to have designs for your project, you will be able to identify these patterns right away. Let's keep this in mind as we get back into exercise mode.

Resolution switching

Here's where all of our knowledge about <picture> (art direction) and srcset and sizes (resolution switching) comes in handy. We'll start with resolution switching because art direction requires additional tooling and configuration.

In Drupal 8 we used the Picture and Breakpoints contrib modules to handle responsive images. Starting with Drupal 9, Drupal provides the "Responsive image" core module which means we don't need to install any contrib modules. Responsive image is not enabled by default.

  1. Enable the Responsive image core module (/admin/modules)
  2. Once enabled, head over to /admin/config/media/responsive-image-style to begin creating our first responsive image style
  3. Click Add responsive image style
  4. Type Content grid as the label for the responsive image style
  5. Select *Responsive image from the Breakpoint group dropdown
  6. Scroll down and select a Fallback image style (16:9 (Max 320px))
  7. Expand the 1x Viewport Sizing [] fieldset
  8. Under Type, chose Select multiple image styles and use the sizes attribute
  9. Under Sizes type the following: (max-width:640px) 100vw, 30vw (I'll explain shortly)
  10. Under Image styles select the image styles we created before
  11. Scroll down and click Save

Image removed.

Let's go over everything we just did

Since we are doing resolution switching and not art direction, we chose Responsive image from the Breakpoint group dropdown. Doing so presents to us the 1x Vieport Sizing [] screen with the following options:

  • Type: Again, since we are doing resolution switching, the obvious choice here is Select multiple image styles and use the sizes attribute. The other two options are irrelevant in this particular example.
  • Sizes: The Sizes option is where we tell the browser how big/small our images should be rendered in relation to the viewport being used. Depending on our goal, this field accepts a single value or a media query with some conditions. Let's say we wanted our images to always render at full width regardless of the device being used (like a Hero image for example), then the value for the Sizes field would be 100vw (100% the viewport width). In our case however, we want the image to display full width, but only if the viewport/device is not larger than 640px, otherwise, meaning if the viewport/device is larger than 640px, we want the image to display at 30% the viewport width. We could had also used a pixel-based value such as 400px for example.
  • Image styles: This is where we choose the image styles we want to make available for the browser to pick from. Think of this as the srcset attribute in the <img> tag.
  • Fallback image: We pick a fallback image in case all the above fails.

Very important: Remember in the Image resolution switching using srcset and sizes attributes post, our claim was that it's better to let the browser pick the best image possible as the browser is smarter than us? This is exactly what we are doing here. We are providing the browser with a collection of images to pick from. Each image provides its dimensions. Then we tell the browser how big/small we want the images to be rendered. One thing we are not doing is telling the browser which image to use, we let the browser make that decision. This is the complete opposite of what we do when we use <picture>. As a reminder, the method used above is what you would do in most of your images. This is like the default configuration for your responsive images. Only when you need to crop your images differently for each device size is when you would use the art direction approach.

Navigate posts within this series

Mario Hernandez: Image styles in Drupal

Now that we've gone over some very important concepts of responsive images (art direction and resolution switching), it's time to transfer all that knowledge and put it all in practice in Drupal. One of the key pieces for achieving responsive images in Drupal is by using image styles. Image styles are how Drupal manages the way we crop and size images.

What are image styles?

Before we get to building image styles, let's go over what they are. Think of image styles as templates for cropping, scaling, converting, and sizing images. You can use these templates with any image on your site and as many times as you'd like. Thanks to image styles images will always render within the parameters we define.

A more real-world way of looking at image styles may be if you could imagine for a moment you have a couple of picture frames you'd like to use to hang some pictures in your house or office. One frame is 5x7, another is 4x6 and one last one is 8x10. The picture frames are Drupal's image styles.

So we have some picture frames and we have ordered several pictures from our favorite online photo printing service. There is one picture in particular I really love and I want to frame it using the 3 picture frames. So, although it is the same picture, I ordered different sizes of it (one for each frame size), and this will allow me to hang the 3 pictures in different sizes, aspect ratios and orientation. That in a nutshell are image styles.

Image removed.

Image styles best practices

Image styles are actually pretty easy to create but unfortunately because of this they can be misused or mismanaged. If not done properly, you may end up with a lot more image styles than you really need or image styles that are not well define and do no provide the outcome you are looking for. To avoid this, let's go over best practices for creating image styles which will result in less image styles to manage. Mind you, these are my best practices but I have to admit, they have worked very well for me.

Naming image styles

Have you heard the phrase "naming things is hard"? It's true. Unfortunately when it comes to image styles, if not named properly you can get yourself in a lot of trouble. Quick example, let's say I want to create an image style that I'd like to use on images of news articles that are displayed on the homepage. One might think a good name for the image style may be something like "Homepage news article images". It doesn't seem so bad but let me point out a few issues with this name:

  • The image style is limited to the homepage
  • It is limited to news article images
  • It lacks information about the image dimensions or aspect ratio

One objective with image styles is to create them in a way that they are reusable. The more reusable an image style is the less image styles you will need to create which in turn becomes easier to manage. The main issue with the image style above ("Homepage news article images"), besides the 3 bullet points we called out, is that is not reusable. The name of it limits us to only use it on the homepage and only for news article images. If we want to display similar images elsewhere, we would need to create another image style maybe with the same parameters as the first one. You may be asking yourself, wait, why can't we use the same image style elsewhere? Technically you can, but think about how confusing it will be to use an image style called "Homepage news article images", not on the homepage and not on news article images.

Creating reusable image styles

One very efficient way for creating reusable image styles is to name them based on the image aspect ratio or dimensions, or a combination of both. For example: "16:9 (Max 320px)", or "Box 1:1 (500px)". Here are some reasons why this is a great way to name image styles:

  • They are not specific to any page or type of image (articles, events, etc.)
  • They provide key information about the image aspect ratio and their dimensions
  • I can use these image styles hundreds of times on any image that fits the requirements as well as on any page
  • By creating/naming image styles this way, I may have just saved myself from creating many other image styles

Identifying the images patterns

I have found one of the most effective ways for identifyiing the image styles you need to create is by looking at your website mockups (if you are fortunate enough to have them). This may not always be possible, but if you do have designs for your website, this will tell you exactly which images you will need and how they need to be rendered. Having this information upfront will help you tremendously when creating image styles because you can plan ahead of time how to create reusable image styles that share commom attributes.

Image styles use cases

When naming image styles it helps me to think of the characteristics of the images I am creating image styles for. For example, I have an image that should be rendered in 16:9 aspect ratio and it should not exceed a width of 320px. This is how I arrived at the name 16:9 (Max 320px). This also makes it possible to know which image style to use if I have other images that need to be rendered similarly. By the way, it is perfectly okay to use an image style that is slightly off from what an image needs to be rendered at. For example, Let's say I have an image that should be rendered at 16:9 aspect ratio, but its size should not exceed 250px. for this image, I can still use the 16:9 (Max 320px) image style.

A 100px or even 200px difference between the image style dimensions and the image you need to use it on it's an acceptable thing to do for a couple of reasons:

  • 100 or 200px in most cases will not make a big of an impact in performance, however, if you are rendering 50 of these images in a single page, then this could certainly present performance issues. So my rule is as long as this is a oneoff type of situation, I'm okay with doing this.
  • Keep in mind that just because your image may be resized larger than it actually needs to be rendered, your image will still visually rendered at the right size as I would suppose it is inside a container that will be sized to the right rendering size, via CSS.
  • Being able to reuse an image style that may be slightly larger than needed saves me from creating more image styles.

I hope you see the impact good names for image styles have on your site. When you are working on an enterprise level website, using the best practices above can really help you with the maintenance of your image styles.

Image styles effects

Effects are the rules you set on each image style. Rules such as cropping, sizing, converting, saturating, rotating, and scaling of images is how we determine how to render the images in our site. In most cases, you want to let content creators of your site upload images that are relatively big. Doing so will allow you to use the images in your library in any use case. It is perfectly okay to scale your images down thorugh the use of image styles, but it is not recommended to scale images up. Doing so will result in blurry or pixelated images. This is why is better to upload large images. But you may be thinking, if I upload super large images, this will affect the performance of my site. It will if you are rendering the original images, but since we are using image styles, Drupal uses the original image to make copies at the size and aspect ratio you defined in your image styles. This is why by uploading a single image you are able to use it in many use cases at different sizes or aspect ratios.

Image styles effects can vary from image style to image style. For example, some image styles will require images to be scaled down, then cropped. Others will require images to be resized then cropped and others may just need for images to be resized to specific size. All these actions are called "Effects" in image styles. The effects you apply to your image styles will depend on the end goal for rendering the images. Let's do a quick demo of creating one image styles then applying effects to it.

Hands-on excercise

All the principles covered in this series apply to Drupal 8, 9, and 10. You can follow along or simply watch me do it. To get started, spin up a vanilla Drupal site of the version of your choice. At the begining of this series I mentioned we will stick with only core/out of the box functionality to keep things simple.

Creating a new image style

  1. Login to Drupal as administrator
  2. In your Drupal site navigate to /admin/config/media/image-styles
  3. Click Add image style
  4. For Image style name type: 16:9 (Max 320px)
  5. To keep things nifty, edit the image style machine name so it reads 16_9_max_320px. (Remove the trailing underscore generated by the ending parenthesis in the image style name. Clean machine names are important to me 😃. It actually makes a difference when you are debugging issues and you find your machine name has an extra underscore you didn't catch).
  6. Click Create new style

Image removed.

The image style above follows the best practices for name we covered earlier. This makes this image style reusable on any image that meets the aspect ratio and dimension requirements.

Adding effects to the image style

For the purpose of this exercise, we are going to use the Scale and crop effect. This is probably the effect I use the most because it does exactly what I want, scale the image down to the size I want and crop it in the aspect ratio I need.

  1. While in the page where the new image style was created (/admin/config/media/image-styles/manage/16_9_max_320px), scroll down and you should see the Effect dropdown
  2. Select Scale and crop from the dropdown
  3. Click Add. The Add Scale and Crop effect screen will come up
  4. Type 320 for width and 180 for height. Note: These two values are required when you select the scale and crop effect. In other effects, these values may not always be required. It is important to define fixed dimensions on your image styles. This ensures your images will be sized/cropped at exactly the size you expect them to. How did I figure out the height for a 16:9 image with a width of 320px is 180px? I used this online aspect ratio calculator.
  5. Notice how you can change the focal point of the cropping by clicking any of the circles under Anchor. For this example we'll keep it in the middle circle.
  6. Click Update effect. This will bring you back to the image style page.
  7. We're done!

Image removed.

Now we have one custom image style with specific effects. If you noticed, Drupal comes with a couple of predefined image styles. If they work for your images you should make use of them. In this series we will be creating custom image styles.

As I mentioned earlier, names of image styles should be descriptive but not limiting. In the case of some of the image styles that come out of the box with Drupal, the names Large, Medium, and Wide do not seem like good choices for names because those names are all relative. Large in relation to what? Medium in relation to what? ...just sayin'.

Image multipliers

One thing we have not discussed but it is very important in responsive images, is the use of "Image Multipliers". What are image multipliers? In responsive images, you often think of image sizes in natural dimensions. If I think of an image that needs to be rendered at 720px, I will most likely resize or crop that image at 720px which makes total sense. With the evolution of high density or high resolution (retina) screens on mobile and larger devices, because they contain thousands or millions more pixels than traditional resolution screens, images need to actually be bigger than the intended size so they are rendered at their highest resolution/quality. This is what image multipliers are.

If we go back to the example above of the 720px image. For this image to be rendered as sharp and high-quality as possible in retina screen devices, we should add a 2x or 3x multiplier to it. Meaning, we should create an image styles for this image at twice and three times the intended size (1440px, 2160px). When we do this, the image will still be rendered at 720px (visually), but because we are providing larger images, these images will have twice or three times the number of pixels within them and when viewed in high resolution screens, the image quality will be superior than if we are only providing a regular 720px image. Note: I typically only create a 2x multiplier image styles for most of my images, but there may be situation when there are specific requirements for creating a 3x multiplier image styles.

Create a 2x multiplier image style

The same way you created the original image style above for 16:9 (Max 320px), go ahead and repeat the process but this time create a 2x multiplier image style, 16:9 (Max 640px). Remember, the dimensions of this image style should be 640 x 360px.

So what's next?

With our custom image styles in place, we can now make use of them, but before we do, let's go over another very important concept within Drupal, Responsive image styles ...whaaaaatttt?
We'll comeback to Drupal in a bit but first, we'll talk about responsive image styles in the next post.

Navigate posts within this series

Mario Hernandez: Image resolution switching using srcset and sizes attributes

In the previous article we defined what art direction is and how to address it using the <picture> element. In this post, the focus will be how to address responsive images when the requirement is image resolution switching. Resolution switching, in the context of responsive images, is rendering identical image content on all devices. Unlike art direction where each device gets a differently cropped image that may vary on aspect ratio, resolution switching uses images that are simply larger or smaller based on the device but retain the same aspect ratio and cropping settings. Resolution switching is how most images are rendered (the rule), the <picture> element approach is the exception to the rule. Take a look at an example of resolution switching below.

Image removed.

The image above demonstrate how multiple resolutions of the same image can be served to different devices. All the images in the example above are cropped exactly the same maintaining the same aspect ratio from large to small.

Using srcset and sizes attributes

Using the srcset and sizes image attributes is how most images are rendered in the web today. As indicated before, this is the recommended way for configuring responsive images if all you need is to switch resolution of images rather than art direction. So how does this approach work? Let's take a look at a typical configuration of the <img> tag using the image above as an example of the different image sizes we will want the browser to choose from:

<img srcset="original-image.jpg 2400w, extra-large.jpg 2000w, large.jpg 1600w, medium.jpg 1080w, small.jpg 800w, x-small.jpg 500w" sizes="100vw" src="large.jpg" alt="Image of sky shown at different resolutions" />

Let's break things down so we can understand this approach better.

  • <img>: Right off the bat we start by using a widely supported html tag.
  • srcset: The srcset attribute in the img tag serves two important roles, 1) It stores a list of images that can be used by the browser, 2) Each image provides its width value which plays a role on the browser choosing the right image.
  • sizes: The sizes attribute tells the browser the width, in relation to the viewport, the image should be rendered at. The value of 100vw shown above, means the image will be rendered at 100% the viewport width on all the devices. You could also use media queries like (max-width: 720px) 100vw, 50vw. This means that if the device does not exceed 720px in width, the image will be rendered at 100% the viewport width, otherwise (if the device is larger than 720px), the image will be rendered at 50% the viewport width.
  • src: The src attribute is used as a fallback if everything fails.

What does it all mean?

Let me explain things in more detail because it is important we understand how this approach is so much better than using the <picture> element.

The biggest difference/advantage of using srcset and sizes versus <picture>, is the fact that we let the browser decide which image is the best image to render on any device. This is possible thanks to all the information we have supplied to the browser. For example, in the srcset we are not only providing the browser with a list of images to choose from, but we are also telling the browser how big each image is. This is very important because the browser will use this information when choosing the image to render. In the <picture> element approach, the image size descriptors are not available.

The sizes value tells the browser the size the image needs to be rendered at in relation to the viewport. This too is extremely important information we are providing the browser because if the browser knows the dimensions of all the images to choose from and how big/small the image needs to be rendered, then the browser is able to pick the best image possible.

But that's not all, the browser is smarter and knows more about the web environment than we do when a page or image is rendered. For example, the browser knows the viewport width used when viewing a website, it knows how fast/slow your internet connection is, and it knows about any browser preference settings (if any), setup by the user. Using all this information the browser is able to determine which image from the srcset is the best to use. In contrast, with the <picture> element, we tell the browser which image to use solely based on the device size.

Closing the gap

Now let's see how using the srcset and sizes attributes closes the gap we identified when using the <picture> tag.

Environment conditions What the developer knows
during development What the browser knows
during image rendering Viewport dimensions No Yes Image size relative to the viewport Yes No Yes via sizes Screen density No Yes Images dimensions Yes No Yes via srcset

Pretty nice huh? Now thanks to the srcset and sizes attributes we've closed the gap and the browser has all the information it needs to ensure the best image is served to each device.

The next post of this series will focus on image styles. These are fun but can also get you in a lot of trouble if not properly done. See you there.

In closing

Time for a story: I recently did an experiment that 100% proves the use of resolution switching using srcset and sizes attributes. As most people nowadays, I use a very large second display when working on projects to fit more apps and see things better. My second display is nice but it's not a 4K display. It's double the physical size of my mac's screen, but the mac's screen resolution is higher by almost double (twice the number of pixels). When I look at an image of a project where I've implemented the practices in this guide, in the large display, and inspected the page, I see the browser has selected an image that is 720px which makes complete sense for the use case I am testing. I then unplugged the second display and viewed the page on my mac's screen (higher resolution), I reloaded the page and inspected it, I noticed the browser has now selected an image that is double the size of the first image. This is exactly the behavior I would expect because my mac screen is of higher resolution and my connection speed is very fast. So the browser was able to make the smart decision to use a different images based on my environment.

Navigate posts within this series

Mario Hernandez: Art Direction using the picture HTML element

In the previous article of this guide we covered the concept of responsive images and some of the challenges that come with implementing an effective system for them. In this article we will go in detail about the concept of "Art Direction" and how this applies to responsive images.

What is art direction?

In the context of responsive images, art direction is the ability to display differently-cropped images based on the device size. For example, a large landscape shot of a person rowing in the middle of a lake is shown when viewed on a large desktop device. If we were to use the same image on a mobile device, that image would shrunk down, making the person in the image very small and hard to see. A better option would be to show a different version of the image that zooms in and focuses on the most important part of the image, the person rowing. See an example of this image below.

Image removed.

Enter the <picture> HTML element

In order to achieve art direction we need to be able to query for the size of the device being used to view the website. Once we've identified the device size we instruct the browser which image to use based on the device size. This will allow us to provide a better user experience as each device will display an image intended specifically for that device. Going back to the image above, we can see that the main image has been cropped differently to ensure the most important part of the image is displayed on each divice.

So how do we query for the device size and how do we instruct the browser which image to use? This is where the <picture> element/tag comes in. Let's take a look at the code that makes all this possible and break it down.

<picture> <source media="(min-width: 2400px)" srcset="images/rowing-2400.jpg 1x, images/rowing-4800.jpg 2x" type="image/webp"> <source media="(min-width: 1280px)" srcset="images/rowing-1400.jpg 1x, images/rowing-2800.jpg 2x" type="image/webp"> <source media="(min-width: 640px) and (max-width: 1279px)" srcset="images/rowing-1200.jpg 1x, images/rowing-2400.jpg 2x" type="images/webp"> <img src="images/rowing-1200.jpg" srcset="images/rowing-2400.jpg 2x" alt="Person rowing on a lake" width="1200" height="800"> </picture>

Note: The order in which the media queries are written within the <picture> tag matters. The browser will use the first match it finds even if it's not the intended one. Therefore, consider the media query order very carefully to ensure the right image is served.

  • <picture>: The <picture> tag is simply a wrapper. On its own it does not do anything.
  • <source>: The <picture> HTML element contains zero or more <source> elements. The browser will consider each child <source> element and choose the best match among them. If no matches are found—or the browser doesn't support the <picture> element—the URL of the <img> element's src attribute is selected. The selected image is then presented in the space occupied by the <img> element.
  • Within the <source> element, you will find some very handy attributes (media, srcset, and type):
    • media: Rembember earlier we said we need to query for the device size? Well, within the media attribute you can write media queries much like the media queries you write in CSS (media="(min-width: 600px)"). This is how we check the size of the device when a page is rendered.
    • srcset: This attribute allows us to provide a list of images the browser can use when the media query finds a match (srcset="img-768.jpg, img-1440.jpg").
    • type: The type attribute specifies a MIME type for the resource URL(s). This is optional if using common image types such as JPG, PNG, TIFF, etc. If you plan on providing images in different file formats, you can do so using the type attribute. This is handy in the event the browser does not support a specific file type (type="image/avif"), as you can then provide a supported file type.
  • <img>: The img element serves two purposes:
    • It describes the dimensions of the image and its presentation
    • It provides a fallback in case none of the offered <source> elements are able to provide a usable image.

And there you have it. The <picture> element is a great way to serve different images based on things like device size or screen density. When the <picture> element was first introduced it required a pollyfill as not all browsers supported it. Nowadays, unless you are supporting Internet Explorer 11 (sorry bro), all other major browsers provide native support for it. Take a look at the chart below for current browser support.

Image removed.

Great! Let's use <picture> on all our images ...NOOOOOOOO!!!!!!

Say what? If the <picture> element is so great, why can't we use it for rendering all of our images? Well, as great as the <picture> element is, it should not be the default solution for serving responsive images in your site. The only use case for the <picture> element is when you are trying to achieve "Art Direction" (cropping your images differently for each device size).

Remember at the begining of this post when I said "In order to achieve art direction we need to be able to query for the device size. Once we've identified the device size we instruct the browser which image to use..."? There lies the problem. Let me explain.

The issue with the statement above is that "we are telling the browser which image". Not only that, but we are doing so solely based on the size of the device. This may not always be the best way to determine which image a device should use. Imagine you are using a nice relatively new laptop with a super high density screen. Based on our rules established within the <picture> element code snippet above, we would end up with an image that is 4800px in size. This is a pretty large image but it's the one that meets our creteria defined in the media query above. If you're home with a decent wifi connection you will never see any issue loading an image this large, but imagine you are working out of a coffee shop, or at a conference with poor wifi connection, or worse yet, you're on the road using your phone as a hotspot and your signal is very bad, now you will really experience some performance issues because we are telling the browser to load the largest image possible because your computer screen is big (relatively speaking). With the <picture> element we can't check how fast your internet connection is, or whether there are browser preferences a user has configured to account for slow internet speeds. We are basing everything on the size of the device.

Then why use the picture element? Well, when developing a website, the developer does not have all the information they need to serve the best image. Likewise, when rendering a page and using the <picture> tag, the browser does not know everything about the environment. The table below shows this in more detail and exposes the gap between the developer and the browser.

Identifying the gap when using <picture>

Environment conditions What the developer knows
during development What the browser knows
during image rendering Viewport dimensions No Yes Image size relative to the viewport Yes No Screen density No Yes Images dimensions Yes No

You may be wondering: "Why did you get us all excited about the <picture> element if we can't really use it?" well, if you are trying to achieve art direction, then you use the <picture> element. It's the recommended approach for that use case. If you are looking for resolution switching, a use case for most images in the web, you need to use the srcset and sizes attributes approach. In the next post we'll dive deep into this technique.

Navigate posts within this series

Mario Hernandez: Responsive images in Drupal - a guide

Images are an essential part of a website. They enhance the appeal of the site and make the user experience a more pleasant one. The challenge is finding the balance between enhancing the look of your website through the use of images and not jeopardizing performance. In this guide, we'll dig deep into how to find that balance by going over knowledge, techniques and practices that will provide you with a solid understanding of the best way to serve images to your visitors using the latest technologies and taking advantage of the advances of web browsers in recent years.

Hi, I hope you are ready to dig into responsive images. This is a seven-part guide that will cover everything you need to know about responsive images and how to manage them in a Drupal site. Although the excercises in this guide are Drupal-specific, the core principles of responsive images apply to any platform you use to build your sites.

Where do we start?

Choosing Drupal as your CMS is a great place to start. Drupal has always been ahead of the game when it comes to managing images by providing features such as image compression, image styles, responsive images styles and media library to mention a few. All these features, and more, come out of the box in Drupal. In fact, most of what we will cover in this guide will be solely out of the box Drupal features. We may touch on third party or contrib techniques or tools but only to let you know what's available not as a hard requirement for managing images in Drupal.

It is important to become well-versed with the tools available in Drupal for managing images. Only then you will be able to make the most of those tools. Don't worry though, this guide will provide you with a lot of knowledge about all the pieces that take part in building a solid system for managing and serving responsive images.

Let's start by breaking down the topics this guide will cover:

  1. What are responsive images?
  2. Art Direction using the <picture> HTML element
  3. Image resolution switching using srcset and sizes attributes
  4. Image styles and Responsive image styles in Drupal
  5. Responsive images and Media
  6. Responsive images, wrapping up

What are responsive images?

A responsive image is one whose dimensions adjust to changes in screen resolutions. The concept of responsive images is one that developers and designers have been strugling with ever since Ethan Marcotte published his famous blog post, Responsive Web Design, back in 2010 followed by his book of the same title. The concept itself is pretty straight forward, serve the right image to any device type based on various factors such as screen resolution, internet speed, device orientation, viewport size, and others. The technique for achieving this concept is not as easy. I can honestly say that over 10 years after reponsive images were introduced, we are still trying to figure out the best way to render images that are responsive. Read more about responsive images.

So if the concept of responsive images is so simple, why don't we have one standard for effectively implementing it? Well, images are complicated. They bring with them all sorts of issues that can negatively impact a website if not properly handled. Some of these issues include: Resolution, file size or weight, file type, bandwidth demands, browser support, and more.

Some of these issues have been resolved by fast internet speeds available nowadays, better browser support for file tyes such as webp, as well as excellent image compression technologies. However, there are still some issues that will probably never go away and that's what makes this topic so complicated. One issue in particular is using poorly compressed images that are extremely big in file size. Unfortunately often times this is at the hands of people who lack the knowledge of creating images that are light in weight and properly compressed. So it's up to us, developers, to anticipate the problems and proactively address them.

Ways to improve image files for your website

If you are responsible for creating or working with images in an image editor such as Photoshop, Illustrator, GIMP, and others, you have great tools at your disposal to ensure your images are optimized and sized properly. You can play around with the image quality scale as you export your images and ensure they are not bigger than they need to be. There are many other tools that can help you with compression. One little tool I've been using for years is this little app called ImageOptim, which allows you to drop in your images in it and it compresses them saving you some file size and improving compression.

Depending on your requirements and environment, you could also look at using different file types for your images. One highly recommended image type is webp. With the ability to do lossless and lossy compression, webp provides significant improvements in file sizes while still maintaining your images high quality. The browser support for webp is excellent as it is supported by all major browsers, but do some research prior to start using it as there are some hosting platforms that do not support webp.

To give you an example of how good webp is, the image in the header of this blog post was originally exported from Photoshop as a .JPG, which resulted in a 317KB file size. This is not bad at all, but then I ran the image through the ImageOptim app and the file size was reduced to 120KB. That's a 62% file size reduction. Then I exported the same image from Photoshop but this time in .webp format and the file size became 93KB. That's 71% in file size reduction compared to the original JPG version.

A must have CSS rule in your project

By now it should be clear that the goal for serving images on any website is doing it by using the responsive images approach. The way you implement responsive images on your site may vary depending on your platform, available tools, and skillset. Regardless, the following CSS rule should always be available within your project base CSS styles and should apply to all images on your site:

img { display: block; max-width: 100%; }

Easy right? That's it, we're done 😃

The CSS rule above will in fact make your images responsive (images will automatically adapt to the width of their containers/viewport). This rule should be added to your website's base styles so every image in your website becomes responsive by default. However, this should not be the extend of your responsive images solution. Although your images will be responsive with the CSS rule above, this does not address image compression nor optimization and this will result in performance issues if you are dealing with extremly large file sizes. Take a look at this example where the rule above is being used. Resize your browser to any width including super small to simulate a mobile device. Notice how the image automatically adapts to the width of the browser. Here's the problem though, the image in this example measures 5760x3840 pixels and it weights 6.7 MB. This means, even if your browser width is super narrow, and the image is resized to a very small visual size, you are still loading an image that is 6.7 MB in weight. No good 👎

In the next post of this series, we will begin the process of implementing a solution for handling responsive images the right way.

Navigate posts within this series

Mario Hernandez: Drupal base path

Recently I was building a component that required a static image which was not stored in the database but instead needed to be stored somewhere in the file system of the site. There are several ways for serving a static image for example we could have stored the image in the sites/default/files/images/ directory. A very common approach which in many cases would work just fine, however, in my case I was building a component and I wanted for the component image to be located within the same component's directory. This makes sense because if I wanted to reuse or share this component, all component assets would be included in a single directory.

Requirements

My goal with this task was to dynamically point to the image regardless the site this component was running on. Oh yeah, we are running a multi-site architecture with hundreds of sites and a single code base. So this component needed to work in all of these hundreds of sites. Now the challenge seems a little more... "challenging".

¡Manos a la hobra'!'

I started by doing research to determine the best way possible to achieve this. I read about using a pre-process function that would generate a dynamic base path of the site but I was hoping I could keep things simple and do everything on the front-end with only Twig. This would make it a more appealing approach for front-end developers.

After some research, I came across two little gems that became game-chargers for my project. One of these gems is the {{ url('<front>') }} Twig function. This will provide the current site's homepage/base path. The other very handy Twig function is {{ active_theme_path() }} which prints the path of the current active theme (themes/custom/my_theme). While researching for this task, I also found you can use the {{ directory }} Twig variable in your theme's templates to print the active theme's path. A word of coution when using either the {{ active_theme_path() }} function of the {{ directory }} variable as these could have different results depending on your whether you are using them in a base or sub theme. Here's a drupal.org issue that discusses this in more detail.
Armed with these two little functions, and one Twig variable, we can now work in generating a dynamic path to our theme's directory where the static image for our component is located. So this may seem like a simple thing but remember, our component's image should work regardless of the site the component is used on within our multi-site architecture. Some sites even use a different sub-theme but the parent theme is always the same which is where our image is stored.

Building the dynamic path

Before we can use the first function we need to run it through the |render Twig filter. Since Twig will return an array from the {{ url() }} function, we need to convert it to a string because we need the value of the function. Let's take a look:

{{ url('<front>')|render }} # This will give us http://my-site.com/

Next let's work with the theme path function. Similarly to the function above, we will use the |render Twig filter to convert it from an array to a string.

{{ active_theme_path()|render }} # This will give us themes/custom/my-theme

Now that we have two strings we can joint them together to compose the full path to our image:

<img src="{{ url('<front>')|render }}{{ active_theme_path()|render }}/images/image.jpg" alt="alt text" />

If we want to get fancy we could actually set a variable to shorten things a bit:

{% set theme_url = url('<front>')|render ~ active_theme_path()|render %} <img src="{{ theme_url ~ '/images/image.jpg' }}" alt="alt text" />

And there you have it. A dynamic path that will work on any of our sites.

I realized some people reading this already knew all of this but I didn't. So I figured I would share it because I bet there are others out there that also do not know about the {{ url('<front>') }} or {{ active_theme_path() }} Twig functions as well as the {{ directory }} variable. As I said before, there are many ways to handle this challenge, but in my case this is exactly how I wanted to approachh it. I hope this was helpful. Cheers!

Mario Hernandez: Flexible Headings with Twig

Proper use of headings h1-h6 in your project presents many advantages incuding semantic markup, better SEO ranking and better accesibility.

Updated April 3, 2020

Building websites using the component based approach presents all kinds of advantages over the traditional page building approach. Today I’m going to show how to create what would normally be an Atom if we use the atomic design approach for building components. We are going to take this simple component to a whole new level by providing a way to dynamically controlling how it is rendered.

The heading component

Headings are normally used for page or section titles and are a big part of making your website SEO friendly. As simple as this may sound, headings need to be carefully planned. A typical heading would look like this:

<h1>This is a Heading 1</h1>

The idea of components is that they are reusable, but how can we possibly turn what already looks like a bare bones component into one that provides options and flexibility? What if we wanted to use a h2 or h3? or what if the title field is a link to another page? Then the heading component would probably not work because we have no way of changing the heading level from h1 to any other level or add a URL. Let's improve the heading component so we make it more dynamic.

Enter Twig and JSON

Twig offers many advantages over plain HTML and today we will use some logic to transform the static heading component into a more dynamic one.

Let’s start by creating a simple JSON object which we will use as data for Twig to consume. We will build some logic around this data to make the heading component more dynamic. This is typically how I build components on projects I work on.

  1. In your project, typically within the components/patterns directory create a new folder called heading
  2. Inside the heading folder create a new file called heading.json
  3. Inside the new file paste the code snippet below
{ "heading": { "heading_level": "", "modifier": "", "title": "This is the best heading I've seen!", "url": "" } }

So we created a simple JSON object with 4 keys: heading_level, modifier, title, and url.

  • The heading_level is something we can use to change the headings from say, h1 to h2 or h3 if we need to.
  • The modifier key allows us to pass a modifier CSS class when we make use of this component. The modifier class will make it possible for us to style the heading differently than other headings, if needed.
  • The title key is the title's string of text that will become the title of a page or a component.
  • ... and finally, the url key, if present, will allow us to wrap the title in an <a> tag, to make it a link.
  1. Inside the heading folder create a new file called heading.twig
  2. Inside the new file paste the code snippet below
<h{{ heading.heading_level|default('2') }} class="heading{{ heading.modifier ? ' ' ~ heading.modifier }}"> {% if heading.url %} <a href="{{ heading.url }}" class="heading__link"> {{ heading.title }} </a> {% else %} {{ heading.title }} {% endif %} </h{{ heading.heading_level|default('2') }}>

Wow! What's all this? 😮

Let's break things down to explain what's happening here since the twig code has changed significantly:

  • First we make use of heading.heading_level to complete the number part of the heading. If a value is not provided for heading_level in the JSON file, we are setting a default of 2. This will ensue that by default we will have a <h2> as the title, much better than <h1> as we saw before. This value can be changed every time the heading isused. The same approach is taken to close the heading tag at the last line of code.
  • Also, in addition to adding a class of heading, we check whether there is a value for the modifier key in JSON. If there is, we pass it to the heading as a CSS class. If no value is provided nothing will be added.
  • In the next line line, we check whether a URL was provided in the JSON file, and if so, we wrap the Flexible Headings with Twig variable in a <a> tag to turn the title into a link. The href value for the link is ``. If no URL is provided in the JSON file, we simply print the value of Flexible Headings with Twig as plain text.

Now what?

Well, our heading component is ready but unfortunately the component on its own does not do any good. The best way to take advantage of our super smart component is to start using it within other components.

Putting the heading component to use

As previously indicated, the idea of components is so they can be reusable which eliminates code duplication. Now that we have the heading component ready, we can reuse it in other templates by taking advantage of twig’s include statements. That will look like this:

<article class="card"> {% include '@components/heading/heading.twig' with { "heading": heading } only %} </article>

The example above shows how we can reuse the heading component in the card component by using a Twig’s include statement.

NOTE: For this to work, the same data structure for the heading needs to exist in the card’s JSON file. Or, you could also alter the heading's values in twig, like this:

<article class="card"> {% include '@components/heading/heading.twig' with { "heading": { "heading_level": 3, "modifier": 'card__title', "title": "This is a super flexible and smart heading", "url": "https://mariohernandez.io" } } only %} </article>

You noticed the part @components? this is only an example of a namespace. If you are not familiar with the component libraries Drupal module, it allows you to create namespaces for your theme which you can use to nest or include components as we see above.

End result

The heading component we built above would look like this when it is rendered:

<h3 class="heading card__title"> <a href="https://mariohernandez.io" class="heading__link"> This is a super flexible and smart heading </a> </h3>

In closing

The main goal of this post is to bring light on how important it is to build components that are not restricted and can be used throughout the site in a way that does not feel like you are repeating yourself.

Additional Resources:

Managing heading levels in design systems.

Mario Hernandez: Adding Social Share Links to Gatsby

Sharing is caring.

I've been working on my personal blog (this site), for a while. I built it with Gatsby and little by little I have been adding extra functionality. Today I'm going to show you how I added social sharing links to allow visitors to share my posts with others using Twitter, Facebook, LinkedIn, and other channels.

For an example of the Sharing links, look at the icons above the hero image on this and every post on this site.

There are many ways to accomplish this but from the begining I wanted to use something that was simple and did not require too much overhead to run. There are solutions out there that require third libraries and scripts and I wanted to avoid that. A while back I was introduced to Responsible Social Share Links. The beauty of Responsible Social Links is that they do not need any Javascript to work. They use the sharing links available for most social media channels.

Let's take a look at some examples of what these links look like:

Facebook

https://www.facebook.com/sharer/sharer.php?u=URL_TO_SHARE

Twitter

<a href="https://twitter.com/intent/tweet/ ?text=Check this out &url=https://mariohernandez.io &via=imariohernandez" target="_blank">Share on Twitter</a>

Most of these links accepts several parameters. You can see these parameters in more details at the Responsible Social Share Links page for additional information. In addtion, some systems may require you to encode the links but luckily for us Reacts does this for us automatically.

Using the links in a Gatsby site (or React for that matter)

You may think, that's so easy, just modify each of the links with my personal information and done. That's true to an extend. However, the tricky part is dynamically passing the current page's URL and post title to your sharing link. So here's how I did it:

  1. Edit your blog post template. In my case my blog post template is /src/templates/blog-post.js This is based on the Gatsby starter I used. Your mileage may vary.

  2. Add the following code where you wish to display the sharing links to generate a twitter share link:

<Share> <ShareLink href={`https://twitter.com/intent/tweet/?text=${post.frontmatter.title} &url=https://mariohernandez.io${post.frontmatter.path}%2F&via=imariohernandez`}> // Optional icon <LinkLabel>Share on Twitter</LinkLabel> </ShareLink> </Share>

The example above creates a twitter share link and uses the data variables I am already using to print the blog post content. As you know, Gatsby uses GraphQL to query the posts and by doing this you have access to each of the fields in your post (i.e. title, path, tags, date, etc.).

In the example above, I am passing ${post.frontmatter.title} so when the post is shared the title of the post is included as your tweet text. In addition, I am linking to the current post by passing ${post.frontmatter.path}. Finally I am passing my twitter handle.

There are other parameters you can pass to your share links. Things like hashtags, mentions, and more. Following the same pattern you can do the same for Facebook, LinkedIn and others.

A much cleaner approach

You may have noticed that I created the sharing snippet directly in the blog-post.js template. A much cleaner approach would be to create a new React component for all yoru sharing links and include the component in your blog-post.js.

Here's the full snippet for all the social channels I am using:

<Share> <ShareLabel>Share this post</ShareLabel> <ShareSocial> <ShareItem> <ShareLink href={`https://twitter.com/intent/tweet/?text=${ post.frontmatter.title }&url=https://mariohernandez.io${post.frontmatter.path}%2F&via=imariohernandez`} > <span> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-twitter" > <path d="M23 3a10.9 10.9 0 0 1-3.14 1.53 4.48 4.48 0 0 0-7.86 3v1A10.66 10.66 0 0 1 3 4s-4 9 5 13a11.64 11.64 0 0 1-7 2c9 5 20 0 20-11.5a4.5 4.5 0 0 0-.08-.83A7.72 7.72 0 0 0 23 3z" /> </svg> </span> <LinkLabel>Share on Twitter</LinkLabel> </ShareLink> </ShareItem> <ShareItem> <ShareLink href={`https://www.facebook.com/sharer/sharer.php?u=https://mariohernandez.io${ post.frontmatter.path }`} target="_blank" > <span> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-facebook" > <path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z" /> </svg> </span> <LinkLabel>Share on Facebook</LinkLabel> </ShareLink> </ShareItem> <ShareItem> <ShareLink href={`https://www.linkedin.com/shareArticle?mini=true&url=https://mariohernandez.io${ post.frontmatter.path }&title=${post.frontmatter.title}&source=${post.frontmatter.title}`} target="_blank" > <span> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-linkedin" > <path d="M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z" /> <rect x="2" y="9" width="4" height="12" /> <circle cx="4" cy="4" r="2" /> </svg> </span> <LinkLabel>Share on LinkedIn</LinkLabel> </ShareLink> </ShareItem> </ShareSocial> </Share>

In Closing

If you want to have a clean and light weight way to share your content with others, the Responsible Sharing Links may just be what you need.

Mario Hernandez: Demystifying components integration with Drupal

Component-based development is something I have been doing for at least five years and it is incredible that I still find myself learning something new every time I work on a new project. In addition to development, I write training curriculums on the topic and this gives me more exposure to this topic than most people. You’d think by now I should have learned all there is to learn about components and integrating them with Drupal, but that’s not the case, and I love it because I alway look forward to learning something new.

The inspiration for this post

I came across an outstanding blog series about Building with Emulsify Part 3: Component Complexity by Evan Willhite of Four Kitchens.

It's not you, it's me

I’d say I’m about 90% onboard with how Evan approaches component integration, but the part I am not a fan of is writing preprocess functions to achieve full integration, mainly because I am not well-versed in preprocess functions or PHP in general. There is absolutely nothing wrong with this, but what if you are someone like me who is not comfortable with preprocess functions or custom modules? So I decided to use most of the work Evan put together, but will perform the integration slightly differently so we only work with Twig and not PHP.

Both instances for which PHP code was required in Evan’s post were the result of using a Paragraph type to reference nodes. My approach will be to eliminate the paragraph type and work directly with the node entity.

Let’s start. I will pick up from Architecture since everything prior to this is typically the approach I take as well.

Architecture

We want administrators to create Nodes of any type and using a Display View Mode we can automatically display them using the card component. The one difference for me is that I don’t have a card variation.

Passing data between entities

Following Evan’s instructions, create a new Display view mode called Card. Here's another minor difference in that my Card uses an image field and date field in addition to title, body, and link fields. Here’s what the card looks like.

Image removed.

In the Card display view mode of an Article content type, ensure Body and Image are available. All other fields should be placed under Disabled. The Title and Date fields don’t display in the Manage Display screens, but they are always available in all Entity templates.

Integrating the Card component within a Node template

Just like in Evan’s post, we still need to associate a Node template with our Card. For this we will use the same template suggestion as Evan, node--card.html.twig.

{% include '@molecules/card/card.twig' with { 'image': content.field_image, 'date': date, 'title': label, 'body': content.body, 'link_url': url, 'link_text': "Read the article", } only %}

Displaying a list of cards with Views

Now that the Card component has been integrated with Drupal, let’s create a simple view to display a collection of nodes displayed as Cards.

The views' settings can be seen below with description of the important configurations to note.

Image removed.

A few things about the view:

  • It’s called Latest Articles
  • The page built by the view can be viewed at /blog
  • Rather than using fields it uses the Card view mode we created earlier. This is the biggest advantage of integrating the Card component with the Entity, any time a node is displayed using the Card Display View Mode, the node will be displayed automatically as a Card.
  • It only pulls nodes of type Article

With some minor CSS the articles would look like this:

Image removed.

In closing

There will be times when writing a preprocess will be required based on the requirements, but whenever possible I’d like to avoid it.