寻求HTML元素(div、类、ID)声明的简洁写法方案
Oh, I feel this pain—typing out those repetitive div class='' or div id='' declarations is such a time sink. Luckily, there are several great options that stick close to standard HTML (or retain angle bracket syntax) while cutting down on boilerplate:
1. Emmet (Built into most code editors)
Emmet is hands-down the easiest solution here—it’s a plugin pre-installed in VS Code, Sublime, Atom, and almost every modern editor. It lets you write shorthand abbreviations that expand directly to full, valid HTML with zero preprocessing beyond hitting Tab.
For your example:
- Type
div.class1>div#id1and press Tab—it expands to:<div class="class1"> <div id="id1"></div> </div>
You can chain elements, add attributes, generate lists, and more with simple shorthand rules. It’s intuitive, requires no new language to learn, and integrates seamlessly with your existing workflow.
2. Slim (Lightweight preprocessor with optional angle brackets)
Slim is a Ruby-based preprocessor that trims unnecessary syntax but still lets you use angle brackets when you want to stick closer to familiar HTML. It uses indentation to replace closing tags, which cuts down on repetition.
Your example can be written in minimal Slim syntax:
div.class1 div#id1
Or if you prefer to keep angle brackets for clarity:
<div class='class1'> <div id='id1'></div> </div>
Slim compiles directly to standard HTML, so browser compatibility isn’t an issue. It’s a great middle ground between pure HTML and more radical templating languages.
3. Haml (Concise preprocessor with optional angle bracket support)
Haml is another popular Ruby-based tool that uses indentation and shorthand to eliminate boilerplate. Like Slim, it supports full HTML tags with angle brackets for edge cases, but its shorthand is even more minimal.
Your example becomes:
.class1 #id1
Which compiles exactly to the HTML you wrote. If you ever need to write a full tag (for complex attributes or edge cases), just use angle brackets normally—Haml will handle it without fuss.
4. HTML5 Custom Elements (For true reusability)
If you want to eliminate repetition entirely rather than just shorten it, HTML5 Custom Elements let you create reusable, self-contained components. For example, define a component for your nested div structure:
class MyNestedDiv extends HTMLElement { connectedCallback() { this.innerHTML = ` <div class='class1'> <div id='id1'></div> </div> `; } } customElements.define('my-nested-div', MyNestedDiv);
Then in your HTML, just write <my-nested-div></my-nested-div> wherever you need that structure. This is pure standard HTML5, no preprocessors required, and perfect for repeated UI patterns in larger projects.
All these options keep your final output as valid, standard HTML, so you don’t have to worry about breaking browser compatibility. Emmet is the quickest to adopt, while Custom Elements offer the most long-term reusability.
内容的提问来源于stack exchange,提问作者Maximilian Travis

