Optimizing Hugo Image Display
Hugo renders Markdown images directly by default. For large images, you can wrap them in a container through an image render hook, then use CSS to improve how they are displayed.
This article uses the PaperMod theme as an example and implements hover zoom with pure CSS, without JavaScript or any third-party library. That way, a failed CDN request cannot break the feature.
Problems with the previous approach
If you only use :active in CSS, an image is enlarged only while the mouse button is held down, and it is hard to trigger on mobile. It also only scales the current image; it does not show a higher-resolution original.
The approach in this article only improves how images are displayed on the page: images keep a responsive width, scale up smoothly on hover, and indicate the current state with a shadow. It does not modify the image files themselves and adds no extra interaction on mobile.
Implementation
1. Create the image render hook
Create layouts/_default/_markup/render-image.html in the site root:
| |
The hook automatically handles Markdown images in posts, such as , so no changes to the post content are needed.
2. Add the CSS
Add the following styles to assets/css/extended/blank.css. If image-related rules already exist in the file, replace them with the rules below so that the old :active styles do not interfere.
| |
If you previously defined custom PaperMod layout widths, you can keep the variable definitions from the original file, for example:
| |
Result and notes
After restarting hugo server and refreshing the page:
- Images never exceed the post content area and adapt to the screen width.
- When an image has
alttext, that text is shown below the image. - On hover, the image scales up smoothly and shows a zoom cursor and a shadow.
- Mobile devices usually have no hover state, so images stay at their normal size and reading is unaffected.
The zoom ratio and animation duration are controlled by scale(1.2) and 0.3s respectively, and can be adjusted to fit the post layout. Since a scaled-up image may overlap adjacent content, it is best not to set the ratio too high.