[Hugo] Center images with URI fragment
How
My website is built with Hugo and Docsy, and I use a URI fragment #center
to indicate that an image should be horizontally centered. Here is an example:
![](images/figuer-1.png#center)
In the _styles_project.scss file, I have the following CSS with the "Attribute Ends With" selector $
:
img[src$="#center"] {
display: block;
margin: 1.0rem auto;
max-width: 100%;
height: auto;
}
The issue
Using the above appoach, images are not centered anymore with Hugo v0.124.x and v0.125.6.
After some tests, I've found that it's because Hugo's built-in image hook removed the URI fragment #center
when converting markdown to HTML.
The generated HTML should look something like below:
<img src="images/figure-1.png#center">
But the result is:
<img src="images/figure-1.png">
I've tried two approaches that can solve this issue. One is to disable the default image hook, and another is to write a custom image hook.
Approach 1: Disable the default image book
According to the Hugo document: Image render hooks, we can disable the default image hook in the site configuration file:
[markup]
[markup.goldmark]
[markup.goldmark.renderHooks]
[markup.goldmark.renderHooks.image]
enableDefault = false
Once the default image hook is disabled, the URI fragment #cener
is correctly rendered in the result HTML, hence images can be centered.
Approach 2: Custom image hook
To learn more about Hugo, I've tried to write a custom image hook to solve this issue. Here is how I do it.
Download the source code of the embeded image render hook and save it as /layouts/_defaul/_markup/render-image.html
. Then modify the file content as below:
|
|
Keep writing!