Can I use a screen size condition for an {if} tag in Liquid code

Hello, I’m wondering if I can make a certain line of code only activate if my media screen is of a certain size or smaller. I was thinking something like combining an IF tag with an @media screen condition. Is this at all possible?

Thanks in advance for the help!

Hi @Worldwidemedals ,

Liquid, being a server-side templating language, does not have the capability to directly respond to client-side properties like screen size. This means you can’t conditionally render different blocks of content in Liquid based on the screen size alone. Any logic in Liquid is executed before the page is sent to the user’s browser, so it doesn’t have access to information like viewport size.
If you need to change content based on screen size, you must rely on CSS or JavaScript, possibly in combination with Liquid.

  1. If you want to make a certain line of html code only for active for mobile, follow this

  

This content is only shown on small screens.

  

This content is only shown on large screens.

In CSS file

/* Hide the desktop block on small screens */
.only-desktop {
  display: none;
}

@media (min-width: 769px) {
  /* Hide the mobile block on large screens */
  .only-mobile {
    display: none;
  }

  .only-desktop {
    display: block;
  }
}
  1. If you want it for Javascript
document.addEventListener("DOMContentLoaded", function() {
  if (window.innerWidth <= 768) {
    // Code for screens 768px wide or smaller
    console.log("Screen is 768px or smaller");
    // Add your JavaScript code here
  } else {
    // Code for screens larger than 768px
    console.log("Screen is larger than 768px");
    // Add your JavaScript code here
  }
});