Ever wanted to know your screen size without using JavaScript? Let’s build a cool little project that displays your screen dimensions using only CSS. Yup, no JavaScript at all — just pure CSS magic.
What We’re Building
We’re creating a small, centered widget that shows the current screen size (width × height) dynamically using custom CSS properties and a sprinkle of math. This is a fun way to explore CSS Houdini features like @property, and you’ll learn something new along the way!
Step 1: Declaring Custom Properties
@property --w_raw {
syntax: '<length>';
inherits: true;
initial-value: 100vw;
}
@property --h_raw {
syntax: '<length>';
inherits: true;
initial-value: 100vh;
}
These lines define custom properties using the @property rule — a newer part of CSS that lets us declare typed, animatable properties. Here, we create:
-w_raw: the width of the viewport (set to 100vw)
–h_raw: the height of the viewport (set to 100vh)
This sets up the foundation for further calculations.
Step 2: Converting to Readable Numbers
root {
--w: tan(atan2(var(--w_raw), 1px));
--h: tan(atan2(var(--h_raw), 1px));
}
This part is a bit trippy. We’re using trigonometric functions (tan and atan2) to convert CSS lengths into values that can be displayed using counter-reset. Basically, this is a hack to turn length values into numbers we can visually show in CSS. While it’s not perfect, it works surprisingly well for simple indicators.
Step 3: Styling the Layout
html, body {
margin: 0;
height: 100%;
}
body {
display: flex;
align-items: center;
justify-content: center;
}
We center everything using Flexbox — nothing fancy, just making sure our indicator is right in the middle of the screen.
Step 4: Displaying the Dimensions
.indicator {
display: flex;
flex-direction: column;
align-items: center;
font-family: system-ui, sans-serif;
}
.indicator::before {
content: counter(w) 'x' counter(h);
counter-reset: h var(--h) w var(--w);
font-size: 3em;
font-weight: 900;
}
Here’s where the magic happens:
The ::before pseudo-element shows the text (like 1280×720).
counter-reset uses our calculated values (–w, –h) to set the width and height counters.
counter(w) ‘x’ counter(h) then prints them as content.
Boom — live dimensions, displayed right on the page!
Final Thoughts
This project is a creative use of cutting-edge CSS features. While it’s not meant for serious production use (for example, it’s not super accurate across all browsers or screen sizes), it’s a great way to experiment with CSS Houdini and show off what CSS can do without any JavaScript.