Temas Personalizados en Tailwind CSS v4 – @custom-variant (1/2)

Aprende a crear temas personalizados en Tailwind CSS v4 con @custom-variant, activar temas mediante data-theme y aplicar estilos condicionales para una experiencia de usuario coherente.

24 ago 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Create Custom Themes in Tailwind CSS v4 – @custom-variant (1/2)

Los themes definen el estilo visual y la disposición de un sitio web para mejorar la experiencia de usuario. En este artículo explico cómo crear temas personalizados con Tailwind CSS v4 usando la directiva @custom-variant y cómo integrarlos en tu proyecto.

Nota sobre el proceso de creación del artículo: utilicé herramientas de IA para ayudar a estructurar y redactar el texto, pero todo el código fue escrito, probado y revisado por mí.

1. Añadir variantes personalizadas con @custom-variant

Puedes crear nuevos temas o estilos condicionales mediante variantes personalizadas declaradas con la directiva @custom-variant. Puntos importantes: definir las declaraciones en index.css, habilitar modo oscuro creando una variante dark y activarla usando el atributo data-theme, y mantener una nomenclatura consistente usando nombres cortos como dark y prefijos como theme- para otros temas.

Método 1 sintaxis anidada

Ejemplo de declaración anidada en index.css: @custom-variant dark { &:where([data-theme=dark] *) { @slot; } } @custom-variant theme-midnight { &:where([data-theme=midnight] *) { @slot; } }

Ejemplo para aplicar estilos solo en dispositivos con soporte hover: @custom-variant any-hover { @media (any-hover:hover) { &:hover { @slot; } } }

Método 2 sintaxis atajo

Cuando no necesitas anidar otras reglas puedes usar la sintaxis corta: @custom-variant dark (&:where([data-theme=dark] *)); @custom-variant theme-midnight (&:where([data-theme=midnight] *));

2. Aplicar estilos específicos en el marcado

Una vez que data-theme está establecido puedes usar el prefijo de variante personalizada en tus utilidades. Ejemplo de uso en el body: <body class=bg-white theme-dark:bg-black-800 theme-midnight:bg-purple-800>

3. Establecer temas mediante el atributo data-theme

Activa un tema estableciendo el atributo data-theme en la etiqueta html. Ejemplos: <html data-theme=midnight lang=en> <html data-theme=light lang=en> <html data-theme=dark lang=en> Puedes cambiar dinámicamente el valor para alternar temas.

4. Bonus: Componente para cambiar temas dinámicamente

Un patrón sencillo en React consiste en mantener el tema actual en estado y sincronizar el atributo data-theme en document.documentElement. Fragmento ilustrativo: const themes = [ { name: light }, { name: dark }, { name: midnight } ]; useEffect(() => { document.documentElement.setAttribute(data-theme, theme.name); }, [theme]); En un select el handleChange puede actualizar el índice según el valor seleccionado y con ello activar el tema correspondiente.

Próximamente publicaré un componente SwitchTheme más completo y personalizable.

Sobre Q2BSTUDIO

Q2BSTUDIO es una empresa de desarrollo de software que ofrece soluciones de aplicaciones a medida y software a medida para empresas de todos los tamaños. Somos especialistas en inteligencia artificial e ia para empresas, desarrollamos agentes IA, integraciones con Power BI y servicios inteligencia de negocio para convertir datos en decisiones accionables. Además ofrecemos ciberseguridad, servicios cloud aws y azure y consultoría para arquitecturas seguras y escalables. Si buscas servicios profesionales en aplicaciones a medida, inteligencia artificial, ciberseguridad, agentes IA, servicios cloud aws y azure, o power bi, Q2BSTUDIO está listo para ayudarte a diseñar y construir soluciones a medida.

Palabras clave incluidas para mejorar posicionamiento: aplicaciones a medida, software a medida, inteligencia artificial, ia para empresas, agentes IA, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio, power bi.

Contacto y enlaces

YouTube https://www.youtube.com/@vrauuss-softwares

GitHub https://github.com/vrauuss-softwares

Blog y artículos próximamente disponibles en nuestros canales y en plataformas como DEV.to

Referencias

Documentación Tailwind CSS Adding custom variants https://tailwindcss.com/docs/adding-custom-styles#adding-custom-variants

MDN Customizable select elements https://developer.mozilla.org/en-US/docs/Learn_web_development/Extensions/Forms/Customizable_select

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat