简体   繁体   English

为什么 CSS 媒体查询在我的 Tailwind/Svelte 项目中不起作用?

[英]Why don't CSS media queries work in my Tailwind/Svelte project?

I have a Svelte project that uses Tailwind CSS for styling.我有一个使用 Tailwind CSS 进行样式设置的 Svelte 项目。 I added the below media query code in the Tailwind CSS file inside @layer components {... } :我在@layer components {... }内的 Tailwind CSS 文件中添加了以下媒体查询代码:

@media only screen and (max-width: 1100) {
  .toggle {
    display: block;
  }
  header nav {
    display: none;
  }
}

But it does not work when I change the width of the browser.但是当我改变浏览器的宽度时它不起作用。

I even checked in inspect element, but it appears as if the media query doesn't even exist in the browser.我什至检查了 inspect 元素,但它看起来好像媒体查询甚至不存在于浏览器中。

Why does the CSS media query not work and how can I fix it?为什么 CSS 媒体查询不起作用,我该如何解决?

If you want your current code to work you need to add "px" to your max-width in media query, like this:如果您希望当前代码正常工作,您需要将“px”添加到媒体查询中的最大宽度,如下所示:

media only screen and (max-width: 1100px)

However, you don't need to do that in tailwind, preferable way would be adding screens to your tailwind.config.js, like this:但是,您不需要在 tailwind 中这样做,更好的方法是将屏幕添加到您的 tailwind.config.js,如下所示:

module.exports = {
  theme: {
    screens: {
      'sm': '640px',
      // => @media (min-width: 640px) { ... }

      'md': '768px',
      // => @media (min-width: 768px) { ... }

      'lg': '1024px',
      // => @media (min-width: 1100px) { ... }

      'xl': '1280px',
      // => @media (min-width: 1280px) { ... }

      '2xl': '1536px',
      // => @media (min-width: 1536px) { ... }
    }
  }
}

In your code you need to do something like this:在您的代码中,您需要执行以下操作:

className='md:block hidden'

Read this page for further info: https://tailwindcss.com/docs/screens阅读此页面以获取更多信息: https://tailwindcss.com/docs/screens

update更新

When working with media queries it is better go with mobile-first approach and use min-width, rather than max-width使用媒体查询时,最好使用移动优先方法 go 并使用最小宽度,而不是最大宽度

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM