Last updated: Apr 6, 2024
Reading time·3 min
You can use the built-in Emmet extension to wrap text with tags in VS Code.
Ctrl
+ Shift
+ P
on Windows and LinuxCommand
+ Shift
+ P
on macOSF1
to open the Command Palette.Enter a tag name, e.g. div
or span
or an abbreviation, e.g.
.container>p
.
Press Enter.
Make sure to select the text you want to wrap before running the command.
You can even wrap text with an abbreviation to add classes, an ID or nest tags.
For example, div.my-class
wraps the text with a div
element that has a class
of my-class
.
<div class="my-class"> hello world </div>
Similarly, you can add multiple classes.
For example, div.class-1.class-2
adds the two classes to the div wrapper.
<div class="class-1 class-2"> hello world </div>
You can wrap text in nested tags. For example div>span>p
produces the
following HTML.
<div> <span> <p>hello world</p> </span> </div>
You can also add classes or attributes to the nested elements, e.g.
div>span.my-class>p
produces the following HTML.
<div> <span class="my-class"> <p>hello world</p> </span> </div>
Use a hash #
to add an id
to a tag, e.g. div#my-id
.
<div id="my-id"> hello world </div>
You can view more examples in the official emmet docs.
You can also add a keyboard shortcut for the "wrap with abbreviation" feature.
The name of the action is called "editor.emmet.action.wrapWithAbbreviation".
To set a keyboard shortcut for the action:
Ctrl
+ Shift
+ P
on Windows and Linux.Command
+ Shift
+ P
on macOS.F1
to open the Command Palette.keybindings.json
file.[ { "key": "alt+w", "command": "editor.emmet.action.wrapWithAbbreviation", "when": "editorHasSelection && editorTextFocus" }, ]
The command binds the action to option ⌥
/Alt
+ W
but you can use any other
key
Now you can use Alt
+ W
to wrap text in tags instead of the command palette.
You can also add the keyboard shortcut using the user interface.
Ctrl
+ Shift
+ P
on Windows and Linux.Command
+ Shift
+ P
on macOS.F1
to open the Command Palette.Search for wrap with abbreviation and double-click on the option.
Press the keys you want to bind the action to and press Enter.
Here is a short gif that demonstrates how to set the keyboard shortcut using the user interface.
If you have difficulties finding the Keyboard shortcuts menu:
Alt
to show the top menu bar.Here is a short gif that demonstrates how to open the Keyboard Shortcuts menu on Windows or Linux.
Note that the Preferences option is under the Code menu on macOS.
If you encounter issues when using Emmet in VS Code, check out my other article:
You can learn more about the related topics by checking out the following tutorials: