How to add media query in Tailwind css?

by katharina , in category: HTML/CSS , 2 years ago

How to add media query in Tailwind css?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by kellie.bechtelar , a year ago

@katharina 

To add a media query in Tailwind CSS, you can use the @apply directive followed by the media query and the style you want to apply within the media query.


Here's an example of how to use the @apply directive to apply a style only when the screen width is at least 640 pixels:

1
2
3
4
5
@media (min-width: 640px) {
  .md:text-xl {
    @apply text-xl;
  }
}


This will apply the text-xl class to an element when the screen width is at least 640 pixels.


You can also use the @screen directive to define your own media query breakpoints and use them throughout your stylesheet. For example:

1
2
3
4
5
6
7
@screen md {
  @media (min-width: 640px) {
    .md:text-xl {
      @apply text-xl;
    }
  }
}


Now you can use the md:text-xl class to apply the text-xl style at the md breakpoint (which is defined as a screen width of at least 640 pixels).


It's also possible to use the @screen directive to define breakpoints in terms of other CSS units, such as em or rem. For example:

1
2
3
4
5
6
7
@screen sm {
  @media (min-width: 30em) {
    .sm:text-xl {
      @apply text-xl;
    }
  }
}


This will apply the text-xl style at the sm breakpoint (which is defined as a screen width of at least 30 em units).

by mazie_pollich , 9 months ago

@katharina 

To add a media query in Tailwind CSS, you can use the @media directive. Here's how you can do it:

  1. Open your project's tailwind.css file.
  2. Locate the section where you want to add the media query. Typically, this would be within a custom CSS class or an existing Tailwind utility class.
  3. Use the @media directive followed by the media query you want to target. For example, to target screens with a maximum width of 768px, you can use @media (max-width: 768px).
  4. Inside the media query, you can add additional CSS rules specific to that media query. These rules will only be applied when the media query condition is met.
  5. Save the changes to the tailwind.css file.


Here's an example of how a media query might be added in Tailwind CSS:

1
2
3
4
5
6
.my-media-query {
  @media (max-width: 768px) {
    /* CSS rules for screens up to 768px */
    /* You can add Tailwind utility classes or custom CSS rules here */
  }
}


Remember to replace .my-media-query with the selector of your choice, and customize the media query condition and CSS rules to fit your needs.