tomw
tomw

Reputation: 98

Change cursor opacity with css

For a touch screen application it may be nice to have the custom cursor fade to opacity = 0 after the screen has not been touched for a while and jump back to opacity = 1 if the screen is touched again.

Is there a way to achieve this with just some css styling?

update: whether or not the cursor is displayed depends on the handling of the underlying system (in particular desktop). As I'm using just a browser on top of a bare X-Server, the cursor is always displayed.

Upvotes: 2

Views: 5839

Answers (1)

Mentalist
Mentalist

Reputation: 1633

While cursor: none is the easiest way to simply hide a cursor, it is also possible to create a cursor with opacity using a .png or .svg.

Here is an example snippet:

.transparent_cursor {
  /* div appearance */
  width: 128px; height: 128px; background-color: #def; background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAF0lEQVQYlWNgYGD4j4YxAB0UDICVKAoAQagf4Vf1Xw0AAAAASUVORK5CYII=");
  
  /* custom cursor */
  cursor: url("data:image/svg+xml,%3Csvg%20version%3D%221.1%22%20id%3D%22pointer_cursor%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20x%3D%220px%22%20y%3D%220px%22%20width%3D%2221px%22%20height%3D%2233px%22%20viewBox%3D%220%200%2021%2033%22%20enable-background%3D%22new%200%200%2021%2033%22%20xml%3Aspace%3D%22preserve%22%3E%3Cpolygon%20id%3D%22outer%22%20opacity%3D%220.5%22%20fill%3D%22%23FFFFFF%22%20points%3D%2220.2%2C20.2%2012.25%2C20.2%2016%2C29%209.667%2C31.75%205.75%2C22.5%200%2C28%200%2C0%20%22%2F%3E%3Cpolygon%20id%3D%22inner%22%20opacity%3D%220.5%22%20fill%3D%22%23231F20%22%20points%3D%226.373%2C19.482%201.75%2C23.904%201.75%2C4.225%2015.975%2C18.45%209.602%2C18.45%2013.708%2C28.087%2010.59%2C29.441%20%22%2F%3E%3C%2Fsvg%3E"), auto;
}
<div class="transparent_cursor"></div>

Keep in mind when designing:

  • The visible "pointer tip" of the image used should start in the upper left corner.
  • If the image needs to be embedded within the CSS itself, you will need to base64 encode - or you can also URL encode for SVG. Using SVG without encoding did not work in my tests.
  • The resolution will be in CSS pixels, so it will look bad on Retina Display. This is true even if SVG is used, because browsers seems to want to want to rasterize in CSS pixels. Bummer.
  • A cursor fallback value such as , auto needs to be included after url(). Details here.

As for animating CSS URLs, I was able to find an example of how this can be achieved. Here's the gist of it:

@keyframes cursor_fade_out {
    0% {cursor: url('cursor_opac100.svg'), auto}
    25% {cursor: url('cursor_opac75.svg'), auto}
    50% {cursor: url('cursor_opac50.svg'), auto}
    75% {cursor: url('cursor_opac25.svg'), auto}
    100% {cursor: url('cursor_opac0.svg'), auto}
}

So you will need to create an image for the cursor at each opacity level.

Upvotes: 1

Related Questions