diff --git a/src/output_xhtml.cpp b/src/output_xhtml.cpp
index f8cd53e478..fe396f83d8 100644
--- a/src/output_xhtml.cpp
+++ b/src/output_xhtml.cpp
@@ -675,7 +675,7 @@ void xhtmlParagraphs(Text const & text,
// If need be, close s, but only at the end of the document (otherwise, dealt with at the beginning
// of the loop).
- while (!headerLevels.empty() && headerLevels.top() > Layout::NOT_IN_TOC) {
+ while (!headerLevels.empty() && headerLevels.top() != Layout::NOT_IN_TOC && headerLevels.top() > 1) {
docstring tag = from_utf8("");
headerLevels.pop();
xs << XMLStream::ESCAPE_NONE << tag;