Search code examples
cssreactjstypescriptjsxtsx

Syntax Highlighting for CSS in a Style Tag in a TSX Component


In my React app, I like to write CSS style within a style tag of a given TSX component. Is there a way to achieve VS Code syntax highlighting for CSS within this context?

Currently, the entire file reflects TSX syntax highlighting, which means the CSS string fragment is all a single color.

I am not using styled-components.

Below is an example of the text I'd like highlighted within the style tag content:

export default function HomeStyle() {
  return (
    <style>{`
    .container {
      min-height: 100vh;
      padding: 0 0.5rem;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
    
    .main {
      padding: 5rem 0;
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
    
    .footer {
      width: 100%;
      height: 100px;
      border-top: 1px solid #eaeaea;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    `}</style>
  );
}


Solution

  • If you use a tagged template literal named css you should get CSS Intellisense & syntax highlighting. eg:

    const css = String.raw;
     
    export default function HomeStyle() {
      return (
        <style>{css`
        .container {
          min-height: 100vh;
          padding: 0 0.5rem;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
        .main {
          padding: 5rem 0;
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
        .footer {
          width: 100%;
          height: 100px;
          border-top: 1px solid #eaeaea;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        `}</style>
      );
    }
    

    If you use a tagged template literal named html you should get HTML Intellisense and syntax highlighting. eg:

    const html = String.raw
    
    const template = html`
      <div class="container"></div>
    `
    

    In these examples I’m using String.raw as a passthrough. Frameworks may provide their own html and css functions to use for this purpose that add framework specific features.