Navigate quickly to a CSS selector in a CSS file directly from an HTML file in Vim with just one keystroke

After reviewing the information I found on Jump to CSS definition when editing HTML in VIM, it unfortunately did not provide the answer I was looking for.

I am interested in being able to easily navigate to the CSS or JavaScript code from an HTML file. Ideally, I would like to simply press a key combination below a word and be taken directly to its definition, rather than having to manually search through open buffers for the desired location. This process currently consumes a significant amount of time.

If anyone has a solution to this common issue, I would greatly appreciate your assistance.

Answer №1

This simple yet effective function provides a solution for navigating from *.html to *.css files:

function! GoToCSS()
  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>')."' **/*.css"
    elseif class_pos > id_pos
      execute ":vim '.".expand('<cword>')."' **/*.css"
    endif
  endif
endfunction

nnoremap <F9> :call GoToCSS()<CR>
  • sample.html

    <html>
      <body>
        <div class="foo" id="bar">lorem</div>
        <div id="bar" class="foo">ipsum</div>
        <div id="bar">dolor</div>
        <div class="foo">sit</div>
      </body>
    </html>
    
  • foo/foo_style.css

    .foo {
      background-color: red;
    }
    
  • bar/bar_style.css

    #bar {
      border-color: gold;
    }
    

By positioning the cursor on any foo or bar attribute value in sample.html, pressing <F9> will direct you to the relevant definition in the corresponding file. This function can be customized to open the target file in a split, scan solely linked stylesheets...or face ZyX's wrath.

edit

Additional tips:

  • :help iskeyword – essential for handling dash-joined names effectively
  • :help expand()
  • :help searchpos() and :help search() – clarifies argument usage
  • :help starstar – explains the ** wildcard feature

Answer №2

This answer deserves its own space, so here it is.

If you want to add CSS support to your ctags and use it to navigate to definitions just like you do for JavaScript, all you need to do is include the following lines in your ~/.ctags file:

--langdef=css
--langmap=css:.css
--regex-css=/^[ \t]*\.([A-Za-z0-9_-]+)/.\1/c,class,classes/
--regex-css=/^[ \t]*#([A-Za-z0-9_-]+)/#\1/i,id,ids/
--regex-css=/^[ \t]*(([A-Za-z0-9_-]+[ \t\n,]+)+)\{/\1/t,tag,tags/
--regex-css=/^[ \t]*@media\s+([A-Za-z0-9_-]+)/\1/m,media,medias/

After setting this up, running :!ctags -R . will properly index your CSS files, allowing you to use :tag .myClass to jump to the correct CSS definition in the appropriate CSS file.

There is one small caveat: the classes and ids tags will have a leading . or #, so using :tag myClass won't work; instead, use :tag /myClass for "regexp search" rather than "whole tag search."

I've found these two mappings to be very effective (working well for JS for some time and recently for CSS):

" Alternative to <C-]>
" Place your cursor on an id or class and press <leader>]
" to jump to the definition
nnoremap <leader>] :tag /<c-r>=expand('<cword>')<cr><cr>

" Alternative to <C-w>}
" Place your cursor on an id or class and press <leader>}
" to display a preview of the definition. While not as useful for CSS,
" it works wonders for JavaScript
nnoremap <leader>} :ptag /<c-r>=expand('<cword>')<cr><cr>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How come I am unable to retrieve it as an object (abonnes) using the GetElementById method from the result?

Why am I not able to retrieve 'abonnes' as an object from the result of GetElementById? The element is available in JSON format. function Abonnes() { const [abonnes, setAbonnes] = useState(); const getOneAbonnes = (id) => { Axios.get( ...

How can I use jQuery to reposition an inner element to the front?

Imagine you have a collection of elements: <ul id="ImportantNumbers"> <li id="one"></li> <li id="two"></li> <li id="topNumber"></li> <li id="four"></li> </ul> Every five seconds, the ...

Close modal using jQuery when the submit button is clicked

My bootstrap modal is quite large. <div className="add-date"> <div className="modal" id="eventSelectedModal" tabIndex="-1" role="dialog" aria-labelledby="myModalLabel1" aria-hidden="true"> <div className="modal-dialog" role="do ...

The implementation of local JSON instead of external JSONP in Angular

I am exploring the option of storing a json-file on the same server as my Angular app. I am wondering about how I can modify this code to read from a locally stored json file: ergastAPI.getDrivers = function() { return $http({ method: 'GET&apos ...

Leveraging jQuery with PHP's POST method

I have limited knowledge in jquery and ajax, but I am in need of a specific functionality on my website. Once users log in successfully, they should be able to download PDF files from the page. There is a collapsible div where users can select which file ...

Encountered an error while setting up a ThreeJS project with Vite on GitHub Pages - received a server response with status code 404

I'm currently facing issues when attempting to deploy my ThreeJS project on GitHub Pages. Despite running the code locally with npm run dev successfully, deploying it on GitHub Pages results in an error message stating "Failed to load resource: the se ...

Adjusting the size of an image based on the size of the window

I'm currently working on my first website project. I have successfully implemented a large image banner, however, I am facing an issue with setting its height. Whenever I try to adjust the height using percentage values, the banner disappears. My goal ...

Detecting a specific button using a variable in jQuery

I've created a function that can identify which post has been clicked on. jQuery(document).ready(function() { jQuery(.recognize-post).on("click", function() { var clickedButton = jQuery(this).data("id") ...

The persistent loading animation in AngularMaterial Autocomplete does not come to an end

Exploring AngularJS and AngularMaterial: Currently, I am delving into the world of AngularJS and experimenting with AngularMaterial. To put it to the test, I decided to create a sample based on the code provided in the documentation (check codepen). My ap ...

Button to close Jquery Dialog

I've set up a custom alert UI using jQuery UI, but I'm having trouble getting the close button to work properly. Here's my code snippet where I'm trying to override the default alert() function with jQuery UI dialog as described in this ...

Tips for processing bound data in AngularJS

Is it possible to manipulate data that is bound with AngularJS after the fact? I am creating a basic search page and have generated the results using this code: ... <div class="row" ng-repeat="document in sc.searchResult.content"> <blockquot ...

Could you please let me know how I can align underneath?

Image description can be found here Your assistance is greatly appreciated, as I am currently inexperienced with React and JavaScript. I am self-studying, so please excuse any basic questions. I have encountered a challenge with this issue. In the image ...

Interacting with jQuery before the doctype declaration can manipulate the text output in various ways

I am currently troubleshooting a PHP application that is displaying a PHP notice. The text appears in the browser before any other content, even before the DOCTYPE declaration. <br /> <b>Notice</b>: Undefined property: bla bla b ...

Does the order property in flex have a specific starting and ending point?

I am curious to know if there are specific start or end numbers for ordering elements within a flex container. For instance: .firstOrder { order: <First-Item> } Why do I ask? Well, I am in the process of developing a CSS framework and I would l ...

"Explore stunning images with the power of JavaScript in our

My question involves a div containing five images, displayed in order as [1] [2] [3] [4] [5]. I am looking to create a JavaScript script that will automatically rearrange the images to display them as [2] [3] [4] [5] [1], then [3] [4] [5] [1] [2], and so o ...

Traverse through an object and set a value to an array of objects only when specific criteria are satisfied - vanilla JavaScript

Consider having an object structured as shown below, with multiple items: myObject:{ item1: { visible: true; }, item2: { visible: true; }, item3: { visible: false; }, } Additionally, there is an array of objects as follows, with potentially n ...

Server-side form validation in Node.js with client-side feedback handling

Express-form is a validation plugin for node.js/express that offers powerful features. However, the examples and documentation currently only show server-side responses (console.log), which may not be very user-friendly. Two possible solutions come to min ...

How can I adjust the position of a target point in the chase camera using THREE.js?

Recently, I've delved into the world of THREE.js and decided to create a game featuring a spaceship as the main element. Utilizing a chase camera for my model, I encountered a challenge where I needed to adjust the camera's position in relation t ...

Zod: Generate a basic item using default settings

I have a strong belief that this concept exists, however, my research has not yielded any results. Let's consider a scenario where I have a zod Schema structured like this: const Person = zod.object({ name: z.string().default(''), ag ...

What is the process of linking this JavaScript code to an outer stylesheet and integrating it with the HTML document?

After encrypting an email address using Hiveware Enkoder, the result can be found below. obfuscated code I typically include it directly inside the div as is. However, I would like to streamline my code by placing it in an external file. While I know ho ...