šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Sharing the CSS breakpoints with JavaScript

Found an interesting technique that allows sharing the CSS breakpoints with the Javascript code. Basically, we want to be able to know in the Javascript code when a CSS media query becomes active.

In order to put it into practice, we will use the before pseudo-element and a resize listener.

First, use the content of before combined with the standard media queries to describe what type of device we are on:

body:before { 
    content: "smartphone"; 
    display: none; /* Prevent from displaying. */ 
} 
@media (min-width: 700px) { 
    body:before { 
        content: "tablet"; 
    } 
}

@media (min-width: 1100px) { 
    body:before { 
        content: "desktop";
    } 
}

After just read that content in a resize lister so that we will know in Javascript what is the screen size:

window.addEventListener('resize', () => {
    const screenType = window.getComputedStyle(document.querySelector('body'), ':before').getPropertyValue('content').replace(/\"/g, ''); };
    if (screenType == 'tablet') { 
        console.log('Tablet breakpoint'); 
    } 
    // more breakpoints here
}

Found it in this older article written by Mike Herchel. He goes into more detail about the implementation in the article.

Or course more direct way is to have the breakpoints values both in CSS and Javascript, but this means we will need to make changes in two files when we want to modify something.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *