How To Write Media Query In Inline Css

Media queries are an essential part of responsive web design. They help you create styles based on specific device characteristics, such as screen width, height, or resolution. However, they’re usually written in separate external or internal CSS files. But what if you need to include a media query within your inline CSS? In this blog post, we’ll explore a solution for this problem, and show you how to write media queries in inline CSS using the style attribute.

The Problem with Media Queries in Inline CSS

Adding a media query directly within the style attribute isn’t possible because media queries require their unique syntax, which isn’t supported by the inline CSS style attribute. They need to be enclosed within @media blocks and placed inside the CSS file or within the style tags.

The Solution: JavaScript

We can solve this problem by using JavaScript to apply the desired styles based on the screen width or other device characteristics. We’ll write a simple function that will check the screen width and apply the corresponding inline style to an element.

Step 1: Create Your HTML Element

First, create the HTML element that you want to style responsively. For example, we’ll use a simple div element with the ID myElement:

This is a responsive element.

Step 2: Write the JavaScript Function

Next, write a JavaScript function that checks the screen width and applies inline styles to your element based on the desired breakpoint. In this example, we’ll change the background color of the div based on the screen width:

function applyMediaQuery() {
var element = document.getElementById(‘myElement’);
var screenWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;

if (screenWidth < 768) {
element.style.backgroundColor = ‘blue’;
} else {
element.style.backgroundColor = ‘green’;
}
}

Step 3: Call the Function on Page Load and Window Resize

Finally, call the applyMediaQuery function when the page loads and whenever the window is resized. This ensures that the styles are applied initially and updated as the screen size changes:

window.addEventListener(‘load’, applyMediaQuery);
window.addEventListener(‘resize’, applyMediaQuery);

Conclusion

While you can’t directly include media queries in inline CSS using the style attribute, you can use JavaScript to apply responsive styles based on screen size or other device characteristics. This approach allows you to create responsive designs even when you’re limited to using inline CSS.