How to create custom media query in tailwind css?

by herminia_bruen , in category: HTML & CSS , 5 months ago

How to create custom media query in tailwind css?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , 5 months ago

@herminia_bruen 

In Tailwind CSS, you can create custom media queries by adding breakpoints to the theme object in your tailwind.config.js file. Here's how you can do it:

  1. Open your tailwind.config.js file.
  2. Inside the file, add a theme object if it doesn't already exist. Inside the theme object, add a screens key with breakpoints and values for your custom media queries. For example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
module.exports = {
  theme: {
    screens: {
      'sm': '640px',
      'md': '768px',
      'lg': '1024px',
      'xl': '1280px',
      '2xl': '1536px',
    },
  },
}


  1. Once you have defined your custom breakpoints, you can use them in your CSS classes like this:
1
2
3
<div class="bg-blue-500 sm:bg-red-500 md:bg-green-500 lg:bg-purple-500 xl:bg-yellow-500 2xl:bg-pink-500">
  <!-- Content here -->
</div>


In the above example, the background color of the div will change based on the screen size. The background color will be blue by default, red on small screens (sm), green on medium screens (md), purple on large screens (lg), yellow on extra-large screens (xl), and pink on 2-extra-large screens (2xl).


By defining custom media queries in this way, you can use them throughout your Tailwind CSS project to create responsive designs that adapt to different screen sizes.