Web Dev Everyday - 19th September 2024🖥️

Daily dose of web dev

Welcome to Web Dev Everyday – your daily dose of 3 minute web development emails.

Let's dive in!

🎯 Tip of the day

Get window size in pure CSS?????

Yes, that’s possible.

Is it easier to do with javascript? Yes.

Is it useful in any way? Maybe 🤔

But it’s good thing to know it’s possible, here we go:

  1. Define Custom Properties

The @property rule lets you create custom properties with specified types, inheritance, and initial values. In this case, we define two custom properties, --w_raw and --h_raw, for the window's width and height:

@property --w_raw {
  syntax: '<length>';
  inherits: true;
  initial-value: 100vw;
}

@property --h_raw {
  syntax: '<length>';
  inherits: true;
  initial-value: 100vh;
}
  1. Remove units

    To convert the window dimensions to unitless values, we can use CSS math functions. We calculate the numeric values of --w_raw and --h_raw using atan2() and tan() :

:root {
  --w: tan(atan2(var(--w_raw), 1px));
  --h: tan(atan2(var(--h_raw), 1px));
}
  1. Display the values

    Finally, you can display the calculated width and height on the page using CSS counters

body::before {
  content: counter(w) ' x ' counter(h);
  counter-reset: h var(--h) w var(--w);
}

Subscribe to keep reading

This content is free, but you must be subscribed to Web Dev Everyday to continue reading.

Already a subscriber?Sign In.Not now