diff --git a/.changeset/thin-wasps-promise.md b/.changeset/thin-wasps-promise.md
new file mode 100644
index 000000000..bcd36e60f
--- /dev/null
+++ b/.changeset/thin-wasps-promise.md
@@ -0,0 +1,5 @@
+---
+'@astrojs/compiler': patch
+---
+
+Fix bug with trailing `style` tags being moved into the `html` element
diff --git a/internal/parser.go b/internal/parser.go
index f52bf0f05..e3a0a1983 100644
--- a/internal/parser.go
+++ b/internal/parser.go
@@ -1107,6 +1107,11 @@ func inBodyIM(p *parser) bool {
p.framesetOK = false
}
case StartTagToken:
+ // if literal and we only have html and body open
+ if p.literal {
+ p.im = inLiteralIM
+ return false
+ }
// It's possible we were moved here from inHeadIM
// via the children of a Component. We need to clear the originalIM
// and switch the implicit `head` tag to `body`
diff --git a/internal/printer/printer_test.go b/internal/printer/printer_test.go
index f00869e9f..7a93cef85 100644
--- a/internal/printer/printer_test.go
+++ b/internal/printer/printer_test.go
@@ -2545,8 +2545,18 @@ const c = '\''
{
name: "style after html",
source: `
Hello world!
`,
+ want: []ASTNode{{Type: "element", Name: "html", Children: []ASTNode{{Type: "element", Name: "body", Children: []ASTNode{{Type: "element", Name: "h1", Children: []ASTNode{{Type: "text", Value: "Hello world!"}}}}}}}, {Type: "element", Name: "style"}},
+ },
+ {
+ name: "style in html",
+ source: `Hello world!
`,
want: []ASTNode{{Type: "element", Name: "html", Children: []ASTNode{{Type: "element", Name: "body", Children: []ASTNode{{Type: "element", Name: "h1", Children: []ASTNode{{Type: "text", Value: "Hello world!"}}}}}, {Type: "element", Name: "style"}}}},
},
+ {
+ name: "style in body",
+ source: `Hello world!
`,
+ want: []ASTNode{{Type: "element", Name: "html", Children: []ASTNode{{Type: "element", Name: "body", Children: []ASTNode{{Type: "element", Name: "h1", Children: []ASTNode{{Type: "text", Value: "Hello world!"}}}, {Type: "element", Name: "style"}}}}}},
+ },
}
for _, tt := range tests {
diff --git a/packages/compiler/test/parse/orphan-head.ts b/packages/compiler/test/parse/orphan-head.ts
index e73c00bf1..4134de684 100644
--- a/packages/compiler/test/parse/orphan-head.ts
+++ b/packages/compiler/test/parse/orphan-head.ts
@@ -27,7 +27,7 @@ test('orphan head', () => {
assert.ok(result, 'able to parse');
const [doctype, html, ...others] = result.ast.children;
- assert.equal(others.length, 0, `Expected only two child nodes!`);
+ assert.equal(others.length, 1, `Expected only three child nodes!`);
assert.equal(doctype.type, 'doctype', `Expected first child node to be of type "doctype"`);
assert.equal(html.type, 'element', `Expected first child node to be of type "element"`);
});