skip to Main Content

I’m a bit confused about something that is hopefully quite simple, I’m extremely new to tailwind CSS, and even after looking into documentation I was not able to find the solution myself.

I have an image that I want visible for larger screen sizes, but hidden for smaller screen sizes.

I tried adding "sm:hidden relative" classNames to an img tag, I expected it to set the img to hidden on devices smaller than 768px.

The Opposite of what I want happens, the img shows on all devices up to 768px, but none bigger

Here is the section of my tailwind.config.cjs with media query overrides;

 screens: {
      xs: "480px",
      ss: "620px",
      sm: "768px",
      md: "1060px",
      lg: "1200px",
      xl: "1700px",
    },

My Img tag is as follows;

  <img src={astronaught} alt="hero-astronaught" className=" z-[5] w-[100%] h-[100%] sm:hidden relative" />

If I only have relative, without the sm:hidden, as expected, the img shows on all devices, if I add the above code, it shows on smaller devices, but not devices larger than 768px, I am extremely confused.

I thought that the way it works logically with sm:hidden relative was "on sm devices, it is hidden, otherwise, it is relative"

Inspecting via console shows that the media query is being applied as follows in full-screen mode;

@media (min-width: 768px)
<style>
.sm:hidden {
    display: none;
}

Inspecting via console during responsive mode for a mobile device, shows no media query at all being applied.

An important thing to note is that I have used these media queries throughout the website and they work fine for padding and margins etc.

Any help would be appreciated, Thanks

Edit: If switching around the order, e.g. hidden sm:visible – then the image does not show on any device. If I inspect the class, it shows that the visible tag is applying, but so is the .hidden class, setting display to none

2

Answers


  1. Chosen as BEST ANSWER

    I managed to find the solution, if I switched the classes to invisible sm:visible, then it worked correctly, but I want hidden, not invisible, as they work a bit differently, and so I realised that the issue was with having relative as my "opposite" to hidden. the new classes go as follows sm:block hidden - Thanks to Sebastion for helping me to properly understand media queries in tailwind!


  2. The way that tailwind media queries work, is that e.g. doing sm:hidden says "for all screens equal or greater than sm: use hidden". So if you do lg:hidden, it counts for both lg and xl and larger, while sm counts for all sizes from sm and up.

    If you want to achieve what you’re describing, I’d simply do the opposite:
    hidden sm:block.

    This will make it show from 768px and up.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search