Custom style to VS code extension

How to add custom style to VS code API extension Webview?

Boldizsar Norbert Benjamin
Nerd For Tech

--

Let's say you want to register a command that opens a basic Webview panel in the editor, with your own CSS design. Visual Studio Code has its own style, but you might as well use your own. The panel uses HTML syntax to display content. We need to keep in mind that the Webview is sandboxed, so all communications are handled by message passing. In our case, we won't be needing any message communication with external JavaScript functions because all we do is link a .css resource into our Webview.

After registering the command that executes our panel, we need to write our HTML code and pass it to the webview.html, which only accepts a plain string as an input. I recommend using a function in which we construct our panel, add style and logic to the used elements, and then assign the constructed string to the webview.html.

This is not necessary but it gives more flexibility for designing and building the panel.

The next step is to create a .css file in your directory, I will create mine in the media local directory folder.

By using the asWebviewUri we can convert our .css file to one that can be used inside Webview, thus giving custom style to our elements.

const myStyle = webview.asWebviewUri(
vscode.Uri.joinPath(
context.extensionUri, 'media', 'my-custom-style.css'
)
);

The Uri can now be linked to our HTML file and by this, we successfully imported our CSS content into the Webview panel.

<link href="${myStyle}" rel="stylesheet" />

For more information consider reading the official documentation of the VS code API:

Developing VS code extensions is not hard, but there are a few difficulties that you need to overcome. I hope that this short tutorial was useful.

Have a great day!

--

--

Boldizsar Norbert Benjamin
Nerd For Tech

iWrite: About[] = [ {name: 'Programming'}, {name: 'Tech'}, {name: 'Something new'} ];