iTranslated by AI
How to Create Elements That Hide Only on Mobile Devices Using Tailwind CSS
Just a small tip.
TL;DR
- TailwindCSS is mobile-first
- You specify styles based on "how it looks on mobile" and "how it looks at a specific breakpoint and above"
- In other words, to make an element disappear only on mobile portrait view (when screen width is small), do this:
<div class="invisible md:visible"></div><div class="hidden md:inline-block"></div>
I wanted to create an element that disappears only on mobile portrait view
There are cases where you want an input element to disappear only in mobile portrait view (when the screen width is narrow).
For example, the search input field when you open YouTube in a browser.
Mobile portrait view
PC or landscape view
You can see that the display of the [Search ] element (and the search button) changes.
I looked into how to achieve this smoothly with TailwindCSS.
TailwindCSS is "Mobile First"
- Mobile First | Responsive Design | TailwindCSS
As stated here:
By default, Tailwind uses a mobile first breakpoint system, similar to what you might be used to in other frameworks like Bootstrap.
What this means is that unprefixed utilities (like uppercase) take effect on all screen sizes, while prefixed utilities (like md:uppercase) only take effect at the specified breakpoint and above.
Where this approach surprises people most often is that to style something for mobile, you need to use the unprefixed version of a utility, not the sm: prefixed version
As described, the basic concept is as follows:
- How does it look on mobile?
- How does it look at the specified breakpoint and above?
Based on this, if you apply TailwindCSS class definitions to create an element that disappears only in mobile portrait view, it would look like this, for example:
<div class="invisible md:visible"></div>
<div class="hidden md:inline-block"></div>
Whether to use invisible or display: none (hidden) depends on your specific requirements.
It works like this. Once you understand the concept, it's not difficult.
Supplement: How to synchronize control in JavaScript
You can also control the display/hiding of buttons and their behavior on click using only TailwindCSS (*1), but how should you align JavaScript-based control with behavior associated with the md: prefix?
It's simple. The default Minimum width for the md: prefix is 768px (which in CSS is @media (min-width: 768px) { ... }), so you can control it with a condition like the following:
if (window.matchMedia('(min-width:768px)').matches) {
// Behavior when the md: prefix is active
}
*1
- For example, the control of the header menu display here is one such case:
- Headers | Official Tailwind CSS UI Components
Discussion