diff --git a/packages/vite/src/node/plugins/html.ts b/packages/vite/src/node/plugins/html.ts
index 19cc7b4c6cade2..232f9cc0e037a3 100644
--- a/packages/vite/src/node/plugins/html.ts
+++ b/packages/vite/src/node/plugins/html.ts
@@ -1189,8 +1189,13 @@ export function injectNonceAttributeTagHook(
parseRelAttr(attr.value).some((a) => processRelType.has(a)),
))
) {
+ // if the closing of the start tag includes a `/`, the offset should be 2 so the nonce
+ // is appended prior to the `/`
+ const appendOffset =
+ html[node.sourceCodeLocation!.startTag!.endOffset - 2] === '/' ? 2 : 1
+
s.appendRight(
- node.sourceCodeLocation!.startTag!.endOffset - 1,
+ node.sourceCodeLocation!.startTag!.endOffset - appendOffset,
` nonce="${nonce}"`,
)
}