Emmet Basics

Emmet AI Overlord Cyborg Anime Girl

My AI overlords asked to me to come up with another blog post. This time it is going to be about Emmet, a tool that was created by web developers to drastically speed up web development process.

The initial idea of Emmet, was conceived by Vadim Makeev in 2009, dubbed Zen Coding, and actively developed by Sergey Chikuyonok ever since. The idea was that we have frameworks for JavaScript, that allow us to speed up JavaScript development, but we didn’t have such tools for HTML and CSS. So out of those ideas Zen Coding and later Emmet was born.

Emmet uses abbreviations and code snippets in CSS-selector like style to expand abbreviations into complex pieces of code. Basically you are writing a shorter representation of longer code, saving time, and making less mistakes.

Using Emmet for HTML

The main reason why Emmet was created is to help front-end developers write HTML more efficiently and accurately. HTML is where Emmet’s capabilities truly shine. This section will demonstrate how Emmet can be used to write abbreviated code that expands into complete HTML structures, with elements, attributes, content, and more, making the development process faster and more streamlined.

Initializers

Emmet has initializers that can help you jumpstart your HTML development with boilerplate code. For example, you can type ! or html:5, and press Tab or Enter to generate an HTML5 boilerplate code.

You can also use your mouse to expand the abbreviation by clicking on the Emmet Suggestions dropdown menu. Once expanded, the boilerplate code will contain highlighted text, indicating areas where you can add your own data. Pressing Tab will cycle through these areas, allowing you to quickly fill them in.

Adding IDs and class attributes

Classes and identifiers (IDs) are used to group and identify elements in HTML and CSS. Emmet allows you to easily add classes and identifiers with a few keystrokes. To add a class or ID to an HTML element with Emmet you use CSS like syntax.

To add a class attribute, use a . followed by the desired class name(s) after the element name. You can specify multiple class names by separating them with a ., like this: div.my-class1.my-class2.

To add an id attribute, simply type a # followed by the desired ID value after the element name. For example, to create a div element with an id of myDiv, you can type div#myDiv and hit Tab or Enter to expand the abbreviation.

You can combine classes and IDs using the same syntax as before. Simply add the # and ., followed by the desired ID and class names respectively. For example, p#foo.bar will generate an HTML paragraph with an id of foo and a class of bar. Similarly, you can specify multiple classes and an ID in the same element, like div#myDiv.my-class1.my-class2. When you use this abbreviation, it will create a div element with an id of myDiv and two class attributes, one with a class name of my-class1 and the other with my-class2.

Defining Content and Attributes for HTML Elements

Emmet lets you easily define content and attributes for HTML elements using special syntax.

To define content, enclose it in curly braces ({}) right after the element name. For example, to create an h1 element with the content “foo”, you can type h1{foo} and hit Tab or Enter to expand the abbreviation. This will produce the following HTML code:

    <h1>foo</h1>

To define attributes, enclose them in square brackets ([]) after the element name. For example, to create an a element with a href attribute set to #, you can type a[href=#] and hit Tab or Enter to expand the abbreviation. This will generate the following HTML code:

    <a href="#"></a>

Nesting

Nesting elements is an essential part of writing HTML, and Emmet makes it easy to create nested elements with a few keystrokes. To nest elements, use the child operator, represented by >, to specify the relationship between parent and child elements. In addition to the child operator, you can also use the sibling operator, represented by +, to place elements next to each other on the same level. For example, to create two paragraphs belonging to the same parent div, you can use the abbreviation div>p+p. This will produce the following HTML:

    <div>
      <p></p>
      <p></p>
    </div>

To put more children inside the parent element you can also use multiplication operator, represented by *. This will create multiple copies of the same child element. For example, to create a ul element with three nested li elements, you can use this abbreviation: ul>li*2. This will produce the following HTML:

    <ul>
        <li></li>
        <li></li>
        <li></li>
    </ul>

In addition to that, you can use the climb up operator, represented by ^, to move up one level in the HTML tree. For example, to create an a element inside a li element, but with a sibling relationship to the ul element, you can use the abbreviation ul>li^a. This will produce the following HTML:

    <ul>
        <li></li>
    </ul>
    <a></a>

Grouping

In Emmet, grouping is used to organize and group pieces of code so they can be nested and expanded properly. The grouping syntax uses parentheses () to encapsulate and group elements together. Similar to mathematical expressions, grouping with parentheses in Emmet can help to prioritize or segregate certain expressions over others.

To use grouping, simply wrap the expressions that you want to group with parentheses. For example, the expression (.foo>h1)+(.bar>h2) groups two sets of expressions, which are (.foo>h1) and (.bar>h2) respectively. When expanded, the abbreviation will generate two sets of HTML code, one for each group:

    <div class="foo">
      <h1></h1>
    </div>
    <div class="bar">
      <h2></h2>
    </div>

Implicit Tag Names

When you use Emmet to create a new element with a class, you can omit the tag name and use only the class name. For example, typing .item will produce <div class="item"></div>.

Emmet uses the parent tag name to determine the implicit tag name to use when expanding the abbreviation. For instance, if you use .item inside a <ul> element, Emmet will create a new list item with a class, like this: <li class="item"></li>.

Emmet provides a few implicit tag names to help you write HTML faster. Here is a list of implicit tag names and the parent elements they apply to:

  • li for ul and ol elements
  • tr for table, tbody, thead, and tfoot elements
  • td for tr elements
  • option for select and optgroup elements

With implicit tag names, you can write more concise and readable code.

Numbering

With Emmet, you can mix the multiplication feature with item numbering to create a list of numbered items. Simply place the $ operator in the element’s name, the attribute’s name or the attribute’s value to output the number of currently repeated elements.

For example, if you type ul>li.item$*3, it will output the following HTML code:

    <ul>
      <li class="item1"></li>
      <li class="item2"></li>
      <li class="item3"></li>
    </ul>

This code creates an unordered list (ul) with three list items (li) that have the class item followed by the corresponding number. The $ operator automatically increments the number for each repeated item. You can also use more than one $ operator to create complex numbering patterns. For example, if you write ul>li.item$$$*3, it will output:

    <ul>
      <li class="item001"></li>
      <li class="item002"></li>
      <li class="item003"></li>
    </ul>

In this example, the first $ operator outputs the current item number, but with three digits (001, 002, 003, etc.), because there are three $ symbols used. This can be useful for creating numbered lists with a specific formatting pattern.

Using Emmet for CSS

While Emmet’s abbreviations are primarily designed for HTML and other structured markup, they can also be used to create shorthands for CSS properties. Instead of manually typing out long CSS property names, Emmet lets you use predefined snippets that expand to the full property name.

For example, you can use the m abbreviation to expand to margin. However, you don’t want to just output the property name - you can also specify a value for it. You can inject a value directly into the abbreviation, like m10 for margin: 10px;.

Emmet also supports injecting multiple values into a single abbreviation, which is very useful for properties that have multiple values. For example, m10-20 expands to margin: 10px 20px;. You can also use negative values by preceding the first value with a hyphen and the rest with double hyphens. For example, m-10--20 expands to margin: -10px -20px;.

Emmet can also automatically add units to the values you provide. If you enter an integer value, it will add a px unit by default. For example, m20 expands to margin: 20px;. If you enter a float value, it will add an em unit by default. For example, m1.5 expands to margin: 1.5em;. If you want to specify a different unit, just add letters right after the value. For example, m1.5ex expands to margin: 1.5ex;.

Emmet also has a few aliases for commonly used values. For example, p stands for %, e stands for em, and x stands for ex. You can use these aliases instead of the full unit names. For example, w100p expands to width: 100%; and m10p30e5x expands to margin: 10% 30em 5ex;.

For properties that have extra options, such as background-image, border-radius, font, @font-face, text-outline, and text-shadow, you can use the + sign to activate these options. For example, @f+ expands to an @font-face rule with more options.

Emmet also has a fuzzy search feature that makes it easier to find the abbreviation you need. If you enter an unknown abbreviation, Emmet will try to find the closest matching snippet definition. For example, ov:h, ov-h, ovh, and oh will all expand to overflow: hidden;.

Finally, Emmet can generate vendor prefixes for CSS3 properties, which can be a real time-saver. For example, the trs abbreviation will expand to -webkit-transform: ; -moz-transform: ; -ms-transform: ; -o-transform: ; transform: ;. You can also define exactly which browser prefixes you want to include, such as -wm-trf for -webkit-transform: ; -moz-transform: ; transform: ;.

Combining CSS abbreviations

By combining abbreviations, you can create complex styles with minimal typing.

For example, the abbreviation fz.675r+1h1.45+p2e+m1r+df+fxd:c+bgc:violet+c:#fff will generate the following CSS code:

    font-size: .675rem;
    line-height: 1.45;
    padding: 2em;
    margin-right: 1rem;
    display: flex;
    flex-direction: column;
    color: #fff;
    background-color: violet;

Here is how it works.

Each abbreviation starts with a property name, such as fz for font-size or p for padding. You can then add values to the abbreviation by using . separator and add additional properties using + separator. The : separator can also be used to specify the property value.

You can use different units for different properties. For example, p2e expands to padding: 2em;, while fz.675r expands to font-size: .675rem;.

Here are some more examples:

  • m1 expands to margin: 1px;
  • p1e expands to padding: 1em;
  • w100p+h100p expands to width: 100%; height: 100%;
  • fxd:c+jc:c+ai:c expands to display: flex; justify-content: center; align-items: center;
  • bgc:#f00+c:#fff expands to background-color: #f00; color: #fff;

When you expand an abbreviation like bgc+c++df+fxd without specifying the values, Emmet will automatically place the cursor at the first property that doesn’t have a value assigned, once the abbreviation is expanded.

You can combine as many abbreviations as you need to create complex styles. Just remember to use the . and : separators to add values, + to add additional properties, and use the appropriate units for each property.

Gradients

Emmet has built-in support for creating CSS gradients, but the autocomplete functionality for gradient functions in VS Code’s implementation of Emmet is currently limited. Several related issues on GitHub (such as https://github.com/microsoft/vscode/issues/79439 and https://github.com/Microsoft/vscode/issues/605) are still unresolved. However, you can supplement Emmet’s limited autocomplete by using one of the many VS Code extensions that provide visual interfaces for generating CSS gradients. For example, extensions like ‘Gradient Generator’, ‘CSS Gradient Generator’, and ‘CSS Gradient’ can all help you create and customize gradients without needing to remember the exact syntax. These extensions typically provide a graphical interface for specifying gradient type, direction, and color stops, and generate the necessary CSS code for you.

Lorem Ipsum

Emmet comes wit build in Lorem ipsum text generator. You just type lorem and press Tab or Enter . By default, it generates around 30 words:

    Lorem ipsum dolor sit, amet consectetur adipisicing elit. Ipsam assumenda voluptatum at temporibus beatae impedit libero natus aperiam sequi deleniti, perferendis repellat, possimus nesciunt ab asperiores atque nostrum molestias nam!

You can also specify how many words you want to generate. For example, lorem 10 will output:

    Lorem ipsum dolor sit amet consectetur adipisicing elit. Nostrum, maxime?

You can also use Lorem in complex Emmet abbreviations. For example ul>li*5>lorem1 will generate unordered list with one word of Lorem per line:

    <ul>
      <li>Lorem.</li>
      <li>Sequi!</li>
      <li>Ipsum.</li>
      <li>Sunt.</li>
      <li>Quaerat!</li>
    </ul>

You can even generate a whole page with Lorem and Emmet! Try this and see:

    html>(head>title{My Web Page})+(body>(header>h1{Header})+(nav>ul>li*4>a{Menu Item $})+(main>(section>h2{Section Title}+(p>lorem50))*3)+(aside>h3{Sidebar Title}+ul>li*5>a{Link $})+(footer>h4{Footer}+p>lorem15))

Sometimes, in cases like the one above, you may need to manually expand an Emmet abbreviation to generate HTML code. To do this, open the Command Palette by pressing Ctrl+Shift+P , search for the Emmet: Expand Abbreviation command, and select it. Pressing Tab or Enter key may not work if you copy and paste some abbreviations or if you somehow interrupt typing the complex abbreviation.

Wrapping with abbreviation

Emmet provides a “Wrap with Abbreviation” command that allows you to quickly wrap an existing piece of code or text with a new HTML tag, specified by an Emmet abbreviation. Here’s how to use it:

  1. Select the text or HTML elements that you want to wrap.

  2. Open the Command Palette by pressing Ctrl+Shift+P .

  3. Type “Wrap with Abbreviation” in the search bar, and select the corresponding command.

  4. Enter the desired tag that you want to use to wrap around the selected text or elements. This can be a standard tag like div, or an abbreviation like .wrapper>p.

  5. Press Enter to apply the wrapping.

Adding Wrap with Abbreviation shortcut

If you frequently use the “Wrap with Abbreviation” command, you can speed up the process by creating a keyboard shortcut. To do this, open the Command Palette by pressing Ctrl+Shift+P and select “Open Keyboard Shortcuts (JSON)”. Then, add the following JSON object to the file:

    {
        "key": "alt+w",
        "command": "editor.emmet.action.wrapWithAbbreviation",
        "when": "editorHasSelection && editorTextFocus"
    }

This configuration creates a custom keyboard shortcut (in this case, alt+w ) that triggers the “Wrap with Abbreviation” command when the shortcut is pressed. The when condition ensures that the shortcut is only active when there is a text selection and the editor has focus.

Wrapping around multiple lines of text

When using Emmet to wrap around multiple lines of text, you can modify the abbreviation syntax to create repeating elements without specifying the exact number of repetitions. For example, you can use an abbreviation like ul#nav>li*>a to create an unordered list with a series of list items, each with a nested link element. When Emmet encounters an element with an undefined multiplication number, it will use the element as a repeating element and output it as many times as there are lines in your selection. The content of each line is placed inside the deepest child of the repeating element, which in this example is the link element.

If you want to wrap an abbreviation like div#header>ul#navigation>li.item$*>a>span around a list of items, such as:

    Home
    Products
    News
    Blog
    About Us
    Contacts

You’ll get the following result:

    <div id="header">
      <ul id="navigation">
        <li class="item1">
          <a href="">
            <span>Home</span>
          </a>
        </li>
        <li class="item2">
          <a href="">
            <span>Products</span>
          </a>
        </li>
        <li class="item3">
          <a href="">
            <span>News</span>
          </a>
        </li>
        <li class="item4">
          <a href="">
            <span>Blog</span>
          </a>
        </li>
        <li class="item5">
          <a href="">
            <span>About Us</span>
          </a>
        </li>
        <li class="item6">
          <a href="">
            <span>Contacts</span>
          </a>
        </li>
      </ul>
    </div>

Overall, using Emmet to wrap around multiple lines of text can be a convenient way to quickly generate HTML structures without having to write out the code manually. By adjusting the abbreviation syntax to match the desired structure, you can create repeating elements and add custom attributes and content to your HTML code with ease.

Creating JavaScript snippet that can be called by using a keyboard shortcut

Here we are going to create a JavaScript snippet that will wrap the selected text in console.log method with some bells and whistles attached.

First we will add JavaScript Emmet snippet to the javascript.json file. Open the Command Palette by pressing Ctrl+Shift+P , type Snippets, select Snippets: Configure User Snippets, then select JavaScript (either create new javascript.json file or use the existing if available) and add the following:

    }
      "console.log": {
        "prefix": "cl",
        "body": [
          "console.${2|log,table,count,dir,error,info|}(${TM_SELECTED_TEXT:`${1}`});",
        ],
        "description": "Log output to console"
      }
    }

This snippet can be triggered by cl and pressing Tab or Enter key. By itself it won’t do much, it will output:

    console.log(``);

And allow you to select a method call. To make this snippet more useful, we will need to be able to call it using a keyboard shortcut, when we selected a text. To do that we need to add a shortcut similar to the one bellow to the keybindings.json file. Open the Command Palette by pressing Ctrl+Shift+P , type Shortcuts, select Open Keyboard Shortcuts (JSON) and add the following:

    {
        "key": "ctrl+alt+q",
        "command": "editor.action.insertSnippet",
        "when": "editorTextFocus",
        "args": {
            "name": "console.log"
        }
    }

This configuration setting creates a custom keyboard shortcut for the code snippet named console.log. The key specifies the keyboard shortcut that triggers the code snippet. The command tells VS Code which command to run when keyboard shortcut is triggered. In this case, it is the “Insert Snippet” command, which allows you to insert the snippet code that you defined earlier into your selected code. The when part specifies the context in which the keyboard shortcut can be triggered. In this case, the shortcut can only be triggered when the focus is on a text editor, and not on a sidebar or other area of the Visual Studio Code interface. The args part provides additional arguments to the command. Specifically, it specifies the name of the code snippet to be inserted (console.log), which in this case is not a built in snippet but a custom snippet we just made. Instead of name you can also specify prefix.

Now, if you select some text, like String(234) and press Ctrl+Alt+Q , you should get this:

    console.log(String(234));

This snippet inserts a console object with a method call, where the method is chosen from a dropdown list of options (in this case,log, table, count, dir, error, or info) and the text to be logged is taken from the selected text in the editor or from the cursor position (if no text is selected).

References

https://docs.emmet.io/ https://docs.emmet.io/cheat-sheet/ https://www.smashingmagazine.com/2013/03/goodbye-zen-coding-hello-emmet/ https://www.smashingmagazine.com/2021/06/custom-emmet-snippets-vscode/ https://www.youtube.com/watch?v=vncch9-1kPE