You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Tailwind CSS 3的媒体查询中同时使用min-width与max-width?

在Tailwind CSS 3中使用同时包含min-width和max-width的媒体查询

这里提供两种实用方法来实现你需要的双条件媒体查询:

方法一:在Tailwind配置中添加自定义区间断点

直接在tailwind.config.js的screens字段里定义包含min和max的断点,之后就能像使用默认断点一样调用它。

修改你的配置文件:

module.exports = {
  content: ["index.html"],
  theme: {
    screens: {
      'sm': '768px',
      'md': '1024px',
      'lg': '1440px',
      // 自定义区间:屏幕宽度≥768px 且 ≤1023px(介于sm和md之间)
      'sm-md': {'min': '768px', 'max': '1023px'},
      // 可按需添加其他区间,比如md到lg之间
      'md-lg': {'min': '1024px', 'max': '1439px'}
    },
  },
}

使用示例:

<div class="bg-white sm-md:bg-blue-500 md:bg-green-500"></div>

生成的CSS会自动转为你想要的格式:

@media screen and (min-width: 768px) and (max-width: 1023px) {
  .sm-md\:bg-blue-500 {
    background-color: #3b82f6;
  }
}

方法二:在自定义CSS中写原生媒体查询结合Tailwind工具类

如果只是偶尔需要某个特定区间,无需修改配置,直接在CSS里写原生媒体查询,用@apply复用Tailwind工具类即可。

示例CSS:

/* 针对768px到1023px的屏幕区间 */
@media screen and (min-width: 768px) and (max-width: 1023px) {
  .custom-section {
    @apply px-6 py-4 rounded-lg bg-gray-100;
  }
}

在HTML中调用:

<section class="custom-section"></section>

内容的提问来源于stack exchange,提问作者Math

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 03:23:26