[Hugo] Center images with URI fragment

Update
2024-05-08: After I post a question on the Hugo discourse site, Joe Mooring replied and confirmed it is a bug in Hugo. He also created a ticket and a pull request for it. Therefore, when his pull request is merged and released, most content of this post will be outdated except the "How" section.

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
{{- $u := urls.Parse .Destination -}}
{{- $src := $u.String -}}
{{- if not $u.IsAbs -}}
  {{- with or (.PageInner.Resources.Get $u.Path) (resources.Get $u.Path) -}}
    {{- $src = .RelPermalink -}}
    {{/* keep the URI fragment "#center" */}}
    {{- with $u.RawQuery -}}
      {{- $src = printf "%s?%s" $src . -}}
    {{- end -}}
    {{- with $u.Fragment -}}
      {{- $src = printf "%s#%s" $src . -}}
    {{- end -}}
  {{- end -}}
{{- end -}}
{{- $attributes := merge .Attributes (dict "alt" .Text "src" $src "title" (.Title | transform.HTMLEscape)) -}}
<img
  {{- range $k, $v := $attributes -}}
    {{- if $v -}}
      {{- printf " %s=%q" $k $v | safeHTMLAttr -}}
    {{- end -}}
  {{- end -}}>
{{- /**/ -}}

Keep writing!

See also

Last modified: 2024-08-20