Vim - Jump to CSS definition from HTLM class or id

Recently I came across a great Vim function on Stack Overflow. Once added to your .vimrc, it allows you to jump from a class or ID within a HTML document directly to the associated styles in your CSS.

Place this function in your .vimrc file:

function! JumpToCSS()
  let id_pos = searchpos("id", "nb", line('.'))[1]
  let class_pos = searchpos("class", "nb", line('.'))[1]

  if class_pos > 0 || id_pos > 0
    if class_pos < id_pos
      execute ":vim '#".expand('<cword>')."' */styles/**/*.scss"
    elseif class_pos > id_pos
      execute ":vim '.".expand('<cword>')."' */styles/**/*.scss"
    endif
  endif
endfunction

I scoped the function's query to my style directory to speed up the search. Simply change */styles/**/*.scss to reference your SCSS/LESS/CSS/etc directory (don't forget to change the extension if you are not using SCSS).

Inside Vim, open a HTML document and place your cursor over a class or ID and run the function by typing:

:call JumpToCSS()

Once the query finishes, Vim will open the file and take you to the correct style definition.


Bonus: If you love your keyboard shorcuts like I do, add a quick shortcut to your .vimrc:

nnoremap <leader>] :call JumpToCSS()

This will allow you to simply hit your leader key followed by a closing bracket: ] to call the function.

Benjamin Charity

Self-motivated UXE technical lead focused on building highly scalable systems for both the web and mobile platforms. Currently focused on Design Language Systems and Component Libraries.