如何修复Django HTML模板继承引发的内容嵌套与页面偏移问题?
Hey there! Let's break down what's going wrong with your template setup and fix that weird nesting/offset problem.
The Core Problem
You've got your template inheritance backwards. The base.html should hold your page's core skeleton (like <!DOCTYPE>, <html>, <head>, <body> tags), while your child template (home.html) only fills in the content specific to that page. Right now, you're shoving an entire full HTML document into the content block of base.html—that's why everything ends up nested incorrectly, and you're seeing those odd rendering glitches.
Step 1: Fix base.html
Update your base template to include the complete page structure, with the content block inside the <body> tag where your page content should live:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Name</title> </head> <body> {% block content %} {% endblock content %} </body> </html>
(Note: I split the meta tags into separate lines for clarity—having both charset and name="viewport" in one meta tag can cause parsing issues too.)
Step 2: Simplify home.html
Your child template only needs to extend the base and fill in the content block with your page-specific content—no need to repeat the full HTML structure:
{% extends "blog/base.html" %} {% block content %} <p>Text</p> {% endblock %}
Bonus: Fix the "Invisible Text" Offset
That slight page offset from invisible text is likely a UTF-8 BOM (Byte Order Mark) at the start of your home.html file. Some text editors add this hidden character when saving as UTF-8. To fix it:
- Open
home.htmlin a code editor like VS Code - Go to the bottom-right encoding selector, click it, choose "Save with Encoding"
- Select "UTF-8 without BOM"
Why This Works
When you use {% extends %}, Django replaces the blocks in the base template with the content from the child template. By putting the full skeleton in base.html, you ensure your page structure is correct every time, and the child template only adds the unique content. Your single-file test worked because it had the proper structure from start to finish—inheritance was breaking it because you duplicated the skeleton.
Give these changes a try, and your page should render exactly like your expected result!
内容的提问来源于stack exchange,提问作者user14794037

