DEV Community

Cover image for Random Transforms Using CSS Variables
Etienne
Etienne

Posted on

Random Transforms Using CSS Variables

CSS variables are fun! They can be used in many different ways, one thing which they are widely used for, is theming. Enabling themes which can be switched back and forth became a whole lot easier with them (as seen on this site ;). I have also published a JS utility, which you can check out here, for this purpose.

But there are even more use cases. We will have a look at using CSS variables deeper down the DOM tree, to transform pseudo elements randomly. Full disclosure I found out about this by looking into how Wes Bos styles the links on his website :D.

Pseudo Elements

We will specifically focus on the :before and :after pseudo elements, which are often used to style an element in ways which are not possible with just one element. Let's assume we have a heading which is also a link to another page (as seen on many blogs). We can give the heading a neat looking border using pseudo elements:



.heading::before {
  content: '';
  background-color: #c1dfc4;
  height: 5px;
  width: 100%;
  position: absolute;
  bottom: 5px;
  left: 0;
  z-index: -1;
  transition: all 0.2s ease-in;
  transform: rotate(-3deg) skewX(-20deg);
}

.heading:hover::before {
  transform: none;
}


Enter fullscreen mode Exit fullscreen mode

Which could look like this:
Alt Text

CSS Variables

Using CSS variables we can not only set variables at the root of our page but deeper down the DOM tree. We could for instance set variables on the heading class:



.heading {
  --rotation: -3deg;
  --skew: -20deg;
}


Enter fullscreen mode Exit fullscreen mode

And then use those variables inside the before pseudo element:



transform: rotate(var(--rotation)) skewX(var(--skew));


Enter fullscreen mode Exit fullscreen mode

Random Transforms

If we put all of this inside a reusable component, in our example using Svelte, we can randomly generate the transforms used on the heading (the following component is abbreviated):



<script>
  const rand = (min, max) => Math.floor(Math.random() * (max - min)) + min
  const style = `
    --rotation: -${rand(1, 5)}deg;
    --skew: -${rand(10, 25)}deg;
  `
  export let href
</script>
<a {href} {style}>
  <slot></slot>
</a>


Enter fullscreen mode Exit fullscreen mode

To see it live in action have a look at this REPL.

Top comments (0)