前端美学 Prompt
让 Claude 生成美观的前端代码
🌐 查看英文原文 | 源码 Notebook
前端美学:Prompt 指南
Claude 可以生成高质量的前端代码,但如果没有引导,它倾向于生成通用的、保守的设计。本指南将展示如何通过 prompt 让 Claude 产出更独特、更精致的输出。
通过 Prompt 获得更好的输出
Claude 对设计原则、排版和色彩理论有很强的知识储备,但除非明确鼓励,否则它会默认选择安全的方案。通过实验,我们发现了三种能够持续产生更好效果的策略:
- 引导特定的设计维度——分别将 Claude 的注意力引导到排版、色彩、动效和背景上
- 引用设计灵感——建议 IDE 主题或文化美学等来源,但不要过于具体
- 指出常见默认行为——明确告诉 Claude 避免其倾向于通用选择的习惯
下面的 prompt 将这些策略应用到了四个关键设计领域。
Prompt
要实现这些更改,你可以将此 prompt 部分附加到你的 system prompt 或 CLAUDE.md 文件中。
DISTILLED_AESTHETICS_PROMPT = """
<frontend_aesthetics>
You tend to converge toward generic, "on distribution" outputs. In frontend design, this creates what users call the "AI slop" aesthetic. Avoid this: make creative, distinctive frontends that surprise and delight. Focus on:
Typography: Choose fonts that are beautiful, unique, and interesting. Avoid generic fonts like Arial and Inter; opt instead for distinctive choices that elevate the frontend's aesthetics.
Color & Theme: Commit to a cohesive aesthetic. Use CSS variables for consistency. Dominant colors with sharp accents outperform timid, evenly-distributed palettes. Draw from IDE themes and cultural aesthetics for inspiration.
Motion: Use animations for effects and micro-interactions. Prioritize CSS-only solutions for HTML. Use Motion library for React when available. Focus on high-impact moments: one well-orchestrated page load with staggered reveals (animation-delay) creates more delight than scattered micro-interactions.
Backgrounds: Create atmosphere and depth rather than defaulting to solid colors. Layer CSS gradients, use geometric patterns, or add contextual effects that match the overall aesthetic.
Avoid generic AI-generated aesthetics:
- Overused font families (Inter, Roboto, Arial, system fonts)
- Clichéd color schemes (particularly purple gradients on white backgrounds)
- Predictable layouts and component patterns
- Cookie-cutter design that lacks context-specific character
Interpret creatively and make unexpected choices that feel genuinely designed for the context. Vary between light and dark themes, different fonts, different aesthetics. You still tend to converge on common choices (Space Grotesk, for example) across generations. Avoid this: it is critical that you think outside the box!
</frontend_aesthetics>
"""效果
以下分别展示了使用和不使用上述 prompt 部分生成 UI 的结果。
在没有引导的情况下,Claude 通常默认使用白紫色背景的简单设计。使用美学 prompt 后,它能生成更多样化、更具视觉吸引力的设计。
示例 1:SaaS 落地页
Prompt: "Create a SaaS landing page for a project management tool"
|
未使用美学 Prompt
|
使用了美学 Prompt
|
示例 2:博客文章
Prompt: "Build a blog post layout with author bio, reading time, and related articles"
|
Without Aesthetics Prompt
|
With Aesthetics Prompt
|
示例 3:管理后台表格
Prompt: "Create an admin panel with a data table showing users, their roles, and action buttons"
|
Without Aesthetics Prompt
|
With Aesthetics Prompt
|
自己动手试试
首先,设置辅助函数:
import html
import os
import re
import time
import webbrowser
from datetime import datetime
from pathlib import Path
from anthropic import Anthropic
from IPython.display import HTML as DisplayHTML
from IPython.display import display
client = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))
def save_html(html_content):
os.makedirs("html_outputs", exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filepath = f"html_outputs/{timestamp}.html"
with open(filepath, "w") as f:
f.write(html_content)
return filepath
def extract_html(text):
pattern = r"```(?:html)?\s*(.*?)\s*```"
matches = re.findall(pattern, text, re.DOTALL)
return matches[0] if matches else None
def open_in_browser(filepath):
abs_path = Path(filepath).resolve()
webbrowser.open(f"file://{abs_path}")
print(f"🌐 Opened in browser: {filepath}")
def generate_html_with_claude(system_prompt, user_prompt):
print("🚀 Generating HTML...\n")
full_response = ""
start_time = time.time()
display_id = display(DisplayHTML(""), display_id=True)
with client.messages.stream(
model="claude-sonnet-4-6",
max_tokens=64000,
system=system_prompt,
messages=[{"role": "user", "content": user_prompt}],
) as stream:
for text in stream.text_stream:
full_response += text
escaped_text = html.escape(full_response)
display_html = f"""
<div id="stream-container" style="border: 2px solid #667eea; border-radius: 8px; padding: 16px; background: #f8f9fa; max-height: 500px; overflow-y: auto;">
<pre style="margin: 0; font-family: monospace; font-size: 12px; color: #2d2d2d; white-space: pre-wrap; word-wrap: break-word;">{escaped_text}</pre>
</div>
<script>
requestAnimationFrame(() => {{
const container = document.getElementById('stream-container');
if (container) {{
container.scrollTop = container.scrollHeight;
}}
}});
</script>
"""
display_id.update(DisplayHTML(display_html))
elapsed = time.time() - start_time
escaped_text = html.escape(full_response)
final_html = f"""
<div style="border: 2px solid #28a745; border-radius: 8px; padding: 16px; background: #f8f9fa; max-height: 500px; overflow-y: auto;">
<pre style="margin: 0; font-family: monospace; font-size: 12px; color: #2d2d2d; white-space: pre-wrap; word-wrap: break-word;">{escaped_text}</pre>
</div>
"""
display_id.update(DisplayHTML(final_html))
print(f"\n✅ Complete in {elapsed:.1f}s\n")
html_content = extract_html(full_response)
if html_content is None:
print("❌ Error: Could not extract HTML from response.")
raise ValueError("Failed to extract HTML from Claude's response.")
filepath = save_html(html_content)
print(f"💾 HTML saved to: {filepath}")
open_in_browser(filepath)
return filepath使用美学 prompt 生成:
BASE_SYSTEM_PROMPT = """
You are an expert frontend engineer skilled at crafting beautiful, performant frontend applications.
<tech_stack>
Use vanilla HTML, CSS, & Javascript. Use Tailwind CSS for your CSS variables.
</tech_stack>
<output>
Generate complete, self-contained HTML code for the requested frontend application. Include all CSS and JavaScript inline.
CRITICAL: You must wrap your HTML code in triple backticks with html language identifier like this:
```html
<!DOCTYPE html>
<html>
...
</html>““”
USER_PROMPT = “Create a SaaS landing page for a project management tool”
Generate with distilled aesthetics prompt
generate_html_with_claude(BASE_SYSTEM_PROMPT + “” + DISTILLED_AESTHETICS_PROMPT, USER_PROMPT)
🚀 Generating HTML…
<IPython.core.display.HTML object>
✅ Complete in 98.2s
💾 HTML saved to: html_outputs/20251021_101010.html 🌐 Opened in browser: html_outputs/20251021_101010.html
‘html_outputs/20251021_101010.html’
## 隔离式 Prompt
完整的美学 prompt 适用于一般场景,但有时你需要更有针对性的控制。你可以隔离特定维度(排版、色彩、动效)或锁定特定主题。这样可以获得更快的生成速度和更可预测的输出。
### 示例 1:仅排版
当你只想改进一个方面而不改变其他方面时,可以隔离单一设计维度:
```python
TYPOGRAPHY_PROMPT = """
<use_interesting_fonts>
Typography instantly signals quality. Avoid using boring, generic fonts.
**Never use:** Inter, Roboto, Open Sans, Lato, default system fonts
**Impact choices:**
- Code aesthetic: JetBrains Mono, Fira Code, Space Grotesk
- Editorial: Playfair Display, Crimson Pro, Fraunces
- Startup: Clash Display, Satoshi, Cabinet Grotesk
- Technical: IBM Plex family, Source Sans 3
- Distinctive: Bricolage Grotesque, Obviously, Newsreader
**Pairing principle:** High contrast = interesting. Display + monospace, serif + geometric sans, variable font across weights.
**Use extremes:** 100/200 weight vs 800/900, not 400 vs 600. Size jumps of 3x+, not 1.5x.
Pick one distinctive font, use it decisively. Load from Google Fonts. State your choice before coding.
</use_interesting_fonts>
"""
# Generate with typography-only guidance
generate_html_with_claude(BASE_SYSTEM_PROMPT + "\n\n" + TYPOGRAPHY_PROMPT, USER_PROMPT)
示例 2:主题约束
当你希望在多次生成中保持一致的主题风格时,可以锁定特定的美学风格:
SOLARPUNK_THEME_PROMPT = """
<always_use_solarpunk_theme>
Always design with Solarpunk aesthetic:
- Warm, optimistic color palettes (greens, golds, earth tones)
- Organic shapes mixed with technical elements
- Nature-inspired patterns and textures
- Bright, hopeful atmosphere
- Retro-futuristic typography
</always_use_solarpunk_theme>
"""
# Generate with theme constraint
generate_html_with_claude(
BASE_SYSTEM_PROMPT + "\n\n" + SOLARPUNK_THEME_PROMPT,
"Create a dashboard for renewable energy monitoring",
)总结
Claude 具有强大的设计能力,但默认倾向于安全、通用的选择。本指南中的技巧——针对特定设计维度、引用具体灵感、明确避免常见默认行为——能够可靠地产生更具特色的输出。完整的美学 prompt 适合作为基线使用。如果需要更多控制,可以使用隔离式 prompt 来关注单个方面,或在多次生成中锁定特定主题。
中文读者提示:本章节的代码和输出为英文原文。如需理解具体实现细节,可参考上方中文导读和代码注释。如有疑问,欢迎在 GitHub Issues 讨论。





