css.Build
- Syntax
- css.Build [OPTIONS] RESOURCE
- css.Build TARGETPATH RESOURCE
- Returns
- resource.Resource
Usage
The css.Build function returns a resource created by bundling the given CSS resource, and optionally transforming and minifying it. It uses the evanw/esbuild package to replace @import statements with the content of the imported files, recursively. If an @import statement includes a media query, a feature query, or a cascade layer assignment, the function wraps the imported content in the corresponding @media, @supports, or @layer rule.
Use these options to process the bundled CSS code further:
- Set the
targetoption to transform syntax and add vendor prefixes for browser compatibility. - Set the
minifyoption to minify the CSS code. - Set the
sourceMapoption to create a source map.
Instead of an options map, you can pass a target path as the first argument. This has the same effect as setting the targetPath option.
Import paths
The paths described below apply to both @import statements and the url() functional notation used for images and fonts.
Each file referenced by a path, including images, fonts, and stylesheets, must reside in the assets directory of the unified file system, or in a Node package in an allowed location as described in file system access.
Files in the assets directory
To import a file from the assets directory, use a bare path, a relative path, or a root-relative path. When you use a bare path, Hugo searches relative to the current stylesheet, then relative to the assets directory.
/* A bare path */
@import "variables.css";
/* A relative path */
@import "./theme.css";
@import "../layout.css";
/* A root-relative path */
@import "/css/grid.css";
/* A url() reference using the same resolution logic */
.logo { background: url("/images/logo.svg"); }Node packages
To import a Node package, use the package name. Hugo reads the package.json file in the package to find the entry point, as described in the mainFields option.
@import "bootstrap";Files in a Node package
To import a specific file from a Node package, use a path that begins with the package name.
@import "bootstrap/dist/css/bootstrap-grid.css";Artifacts
New in v0.165.0In addition to the main output, Hugo may publish other files as part of the build:
- Files copied to the output directory by the
fileloader, such as fonts and images - A source map, when the
sourceMapoption isexternalorlinked
To access these files, call the Data method on the returned resource. The resulting map contains an Artifacts key, a slice with one artifact for each file. Use these methods on each artifact:
MediaType- (
media.Type) Returns the media type of the file. Permalink- (
string) Returns the permalink of the file. RelPermalink- (
string) Returns the relative permalink of the file.
File system access
Hugo limits the files that this function can import from outside the assets directory to the paths in security.node.permissions.allowRead. By default, this is the project directory, including its node_modules directory. To import files from other locations, such as the node_modules directory of a parent directory in a monorepo, add those paths to the list.
Options
The css.Build function accepts an options map.
charset- New in v0.168.0
- (
string) The character set of the generated CSS code, eitherasciiorutf8. Hugo escapes characters outside of this set. Default isascii. externals- (
[]string) A slice of paths to exclude from bundling. Hugo leaves the matching@importstatements unchanged in the generated CSS code. How Hugo matches each path depends on where the imported file resides:- For a file in the
assetsdirectory, the path must exactly match the path in the@importstatement, such as./vendor/legacy.css. - For a Node package, the path can be a package name, such as
bootstrap, which also matches every file in the package. The path can also contain one*wildcard, such asboot*.
{{ $opts := dict "externals" (slice "./vendor/legacy.css" "bootstrap") }} {{ $r := resources.Get "css/main.css" | css.Build $opts }} - For a file in the
importContext- New in v0.165.0
- (
resource.ResourceGetter) A resource getter to use when resolving@importstatements. Hugo searches this context first, before falling back to the file system. Hugo matches a resource in the context by the path relative to theassetsdirectory. For a path that begins with./or../, Hugo resolves the path relative to the importing file. For example, when theassets/css/main.cssfile contains@import "./sub/theme.css", a resource namedcss/sub/theme.cssmatches. For a bare path, Hugo also tries the path as written, so@import "sub/theme.css"matches a resource namedsub/theme.cssorcss/sub/theme.css. loaders- (
map) A map of file extensions to loader types. The loader type determines how Hugo processes files with a given extension during bundling. Values in this map override the defaults, which are:- The
cssloader for.cssfiles - The
fileloader for image files with the.avif,.gif,.jpeg,.jpg,.png,.svg, or.webpextension - The
fileloader for font files with the.eot,.otf,.ttf,.woff, or.woff2extension
The build fails if a
url()references a file with any other extension, such as.ico, unless you map the extension to a loader. Common loaders include:css: Processes the file as a CSS filedataurl: Embeds the file in the generated CSS code as a data URLempty: Replaces the reference with an emptyurl()file: Copies the file to the output directory and rewrites the URL
{{ $opts := dict "loaders" (dict ".png" "dataurl" ".svg" "dataurl") }} {{ $r := resources.Get "css/main.css" | css.Build $opts }} - The
mainFields- (
[]string) A prioritized slice of field names in apackage.jsonfile that determine the CSS entry point of a Node.js package. Default is["style", "main"].When an
@importstatement references a Node package, Hugo reads thepackage.jsonfile to find the stylesheet. Use this option to support packages that define a CSS entry point using non-standard fields.{{ $opts := dict "mainFields" (slice "css" "style" "main") }} {{ $r := resources.Get "css/main.css" | css.Build $opts }} minify- (
bool) Whether to minify the generated CSS code. Default isfalse.{{ $opts := dict "minify" true }} {{ $r := resources.Get "css/main.css" | css.Build $opts }} sourceMap- (
string) The type of source map to generate, one ofexternal,inline,linked, ornone. Default isnone.{{ $opts := dict "sourceMap" "linked" }} {{ $r := resources.Get "css/main.css" | css.Build $opts }} sourcesContent- (
bool) Whether to include the content of the source files in the source map. Default istrue.{{ $opts := dict "sourceMap" "linked" "sourcesContent" false }} {{ $r := resources.Get "css/main.css" | css.Build $opts }} target- (
stringor[]string) The target environment for the generated CSS code. The target environment determines which syntax transformations to perform and which vendor prefixes to add. If unset, Hugo does not transform syntax or add vendor prefixes. Each value consists of a target name followed by a version number, such aschrome115. Supported targets includechrome,edge,firefox,ie,ios,opera, andsafari. Target names are case-insensitive. The build fails if a target name lacks a version number, or if Hugo does not recognize any of the values. Hugo ignores an unrecognized value if it recognizes another value in the slice.{{ $target := slice "chrome115" "edge115" "firefox116" "ios16.4" "safari16.4" }} {{ $opts := dict "target" $target }} {{ $r := resources.Get "css/main.css" | css.Build $opts }}This target environment matches the desktop and iOS browsers in the Browserslist “baseline widely available” query as of March 2026.
targetPath- (
string) The target path of the resource, relative to thepublicdirectory. If unset, the target path defaults to the asset’s original path with a.cssextension.{{ $opts := dict "targetPath" "css/styles.css" }} {{ $r := resources.Get "css/main.css" | css.Build $opts }} vars- New in v0.160.0
- (
map) A map of key-value pairs used to generate CSS variables. Thecss.Buildfunction injects these variables into the stylesheet when it finds thehugo:varsinternal identifier in an@importstatement.{{ $vars := dict "font-family" "\"Times New Roman\", Times, serif" "font-size" "24px" "primary-color" "blue" }} {{ $opts := dict "vars" $vars }} {{ $r := resources.Get "css/main.css" | css.Build $opts }}Import the
hugo:varsidentifier in your stylesheet to access the values with standard CSS variable syntax:@import 'hugo:vars'; .element { color: var(--primary-color); font-family: var(--font-family); font-size: var(--font-size); }The above produces output equivalent to:
New in v0.161.0:root { --font-family: "Times New Roman", Times, serif; --font-size: 24px; --primary-color: blue; } .element { color: var(--primary-color); font-family: var(--font-family); font-size: var(--font-size); }The map can contain nested maps. Hugo exposes each nested map as a separate
hugo:vars/<name>namespace, where<name>is the key of the nested map converted to lowercase. Top-level scalar values and nested maps are independent. An@import 'hugo:vars'statement includes only the top-level scalar values, and an@import 'hugo:vars/<name>'statement includes only the scalar values from the named nested map.{{ $vars := dict "font-family" "\"Times New Roman\", Times, serif" "font-size" "24px" "primary-color" "blue" "mobile" (dict "font-size" "12px" "primary-color" "red" ) }} {{ $opts := dict "vars" $vars }} {{ $r := resources.Get "css/main.css" | css.Build $opts }}Nested imports follow the same rules as other
@importstatements, so you can add a media query, a feature query, or a cascade layer assignment to ahugo:vars/<name>import:@import 'hugo:vars'; @import 'hugo:vars/mobile' (max-width: 650px); body { background-color: var(--primary-color); font-family: var(--font-family); }The above produces output equivalent to:
:root { --font-family: "Times New Roman", Times, serif; --font-size: 24px; --primary-color: blue; } @media (max-width: 650px) { :root { --font-size: 12px; --primary-color: red; } } body { background-color: var(--primary-color); font-family: var(--font-family); }Use the
varsoption to set CSS variables in your project configuration:params: theme: style: font-family: '"Times New Roman", Times, serif' font-size: 24px mobile: font-size: 12px primary-color: red primary-color: blue[params] [params.theme] [params.theme.style] font-family = '"Times New Roman", Times, serif' font-size = '24px' primary-color = 'blue' [params.theme.style.mobile] font-size = '12px' primary-color = 'red'{ "params": { "theme": { "style": { "font-family": "\"Times New Roman\", Times, serif", "font-size": "24px", "mobile": { "font-size": "12px", "primary-color": "red" }, "primary-color": "blue" } } } }Then pass the configuration values to the
css.Buildfunction:{{ $opts := dict "vars" site.Params.theme.style }} {{ $r := resources.Get "css/main.css" | css.Build $opts }}Use the
css.Quotedfunction to treat a value as a quoted string, most commonly forfont-familynames or thecontentproperty.You can also use the
varsoption to inject CSS variables into a stylesheet that you process with Tailwind CSS.
Examples
These examples bundle imported files, apply several options, and render preload links for the font files published by the build.
Bundle imported files
This example bundles the local files referenced by @import statements into a single resource:
assets/
└── css/
├── components/
│ ├── a.css
│ └── b.css
└── main.cssThe CSS entry file:
@import url('https://cdn.jsdelivr.net/npm/the-new-css-reset/css/reset.min.css');
@import './components/a.css';
@import './components/b.css';
.c { color: blue; }The imported files:
.a { color: red; }.b { color: green; }A partial template to process the CSS:
{{ with resources.Get "css/main.css" | css.Build }}
{{ if hugo.IsDevelopment }}
<link rel="stylesheet" href="{{ .RelPermalink }}">
{{ else }}
{{ with . | fingerprint }}
<link rel="stylesheet" href="{{ .RelPermalink }}" integrity="{{ .Data.Integrity }}" crossorigin="anonymous">
{{ end }}
{{ end }}
{{ end }}Calling the partial template from the base template:
{{ partialCached "css.html" . }}The generated CSS code in development, in which the external URL import remains unchanged:
@import "https://cdn.jsdelivr.net/npm/the-new-css-reset/css/reset.min.css";
/* ns-hugo-imp:/home/user/project/assets/css/components/a.css */
.a {
color: red;
}
/* ns-hugo-imp:/home/user/project/assets/css/components/b.css */
.b {
color: green;
}
/* <stdin> */
.c {
color: blue;
}Unless you set the minify option to true, the generated CSS code includes a comment before the content of each source file. The comment for an imported file contains its absolute path on the computer that builds the site. In production, the fingerprint function adds a hash to the file name, such as main.5913efb7…841b.css.
Bundle, transform, and minify
This example uses several options to bundle, transform, and minify the CSS code:
{{ with resources.Get "css/main.css" }}
{{ $opts := dict
"loaders" (dict ".png" "dataurl" ".svg" "dataurl")
"minify" (cond hugo.IsDevelopment false true)
"sourceMap" (cond hugo.IsDevelopment "linked" "none")
"target" (slice "chrome115" "edge115" "firefox116" "ios16.4" "safari16.4")
"targetPath" "css/styles.css"
}}
{{ with . | css.Build $opts }}
{{ if hugo.IsDevelopment }}
<link rel="stylesheet" href="{{ .RelPermalink }}">
{{ else }}
{{ with . | fingerprint }}
<link rel="stylesheet" href="{{ .RelPermalink }}" integrity="{{ .Data.Integrity }}" crossorigin="anonymous">
{{ end }}
{{ end }}
{{ end }}
{{ end }}With these options, Hugo does the following:
- Embeds PNG and SVG images as data URLs in the generated CSS code
- Minifies the output in production but not in development
- Generates a linked source map in development but not in production
- Transforms syntax for compatibility with the targeted browser versions
- Adds vendor prefixes for compatibility with the targeted browser versions
- Publishes the generated CSS code to
css/styles.css - In production, adds an SRI hash and inserts a file hash into the file name
Render preload links for fonts
This example renders a preload link for each font file that the build publishes, using the artifacts of the returned resource:
{{ with resources.Get "css/main.css" }}
{{ with . | css.Build }}
{{ range .Data.Artifacts }}
{{ if eq .MediaType.MainType "font" }}
<link rel="preload" href="{{ .RelPermalink }}" as="font" type="{{ .MediaType.Type }}" crossorigin>
{{ end }}
{{ end }}
<link rel="stylesheet" href="{{ .RelPermalink }}">
{{ end }}
{{ end }}