Search code examples
htmlcssvariablessass

How to change font size variable on hover CSS


I'm new to CSS variable manipulation and haven't found an answer to a problem I'm facing. I have two separate font sizes depending on screen width. I'd like to dynamically increase these variables on hover. How can I do this? Is there a better way in general?

$my-font-size: 1rem;
h1 {
  font-size: calc($my-font-size * 1.25);
}

@media only screen and (max-width: 595px) {
  h1 {
    font-size: $my-font-size;
  }
}

h1:hover {
  $my-font-size: calc($my-font-size * 1.15);
}

  


Solution

  • Just define the variable for the font-size before and inside the media query. Then use calc to multiply the font-size on hover with the variable:

    :root {
      --font-size: 1.25rem;
    }
    
    @media only screen 
      and (max-width: 595px) {
        :root {
          --font-size: 1rem;
        }
    }
    
    h1 {
      font-size: var(--font-size);
    }
    
    h1:hover {
      font-size: calc(var(--font-size) * 1.15);
    }
    <h1>Just a Test</h1>