Here’s the documentation for implementing similar state-based styling using only HTML and CSS without a CSS framework:
Introduction
This guide demonstrates how to implement state-based styling similar to what
@flexilla/uno-preset
or @flexilla/tailwind-plugin
provide, using only HTML and CSS. We will focus on managing element states like
open
, active
, visible
, etc., using the data-state
attribute for simplicity. Defining State-Based Styles
We’ll directly use attribute selectors in CSS. For example, to apply styles based on a
data-state
attribute, we can write the following: Available States
Here are the states we will use for demonstration:
-
open
-
closed
-
active
-
inactive
-
visible
-
hidden
Example 1: Open and Close States
HTML
<div data-state="open" class="box">
Open State Content
</div>
<div data-state="closed" class="box">
Closed State Content
</div>
CSS
/* Style for open state */
[data-state="open"] {
background-color: green;
color: white;
}
/* Style for closed state */
[data-state="closed"] {
background-color: red;
color: white;
}
In this example, elements with
data-state="open"
are styled with a green background, while elements with data-state="closed"
have a red background. Example 2: Active and Inactive States
HTML
<div data-state="active" class="button">
Active Button
</div>
<div data-state="inactive" class="button">
Inactive Button
</div>
CSS
/* Style for active state */
[data-state="active"] {
background-color: blue;
color: white;
}
/* Style for inactive state */
[data-state="inactive"] {
background-color: gray;
color: white;
}
Example 3: Visibility States
HTML
<div data-state="visible" class="popup">
Visible Content
</div>
<div data-state="hidden" class="popup">
Hidden Content
</div>
CSS
/* Style for visible state */
[data-state="visible"] {
display: block;
}
/* Style for hidden state */
[data-state="hidden"] {
display: none;
}
Here, content with
data-state="hidden"
is hidden from view using display: none
. In this case, the button with both
data-state="active open"
will be styled with a dark green background and yellow text. Example 5: Transition and Animation
For dynamic interactions like modals or tab panels, you can use CSS transitions or animations.
HTML
<div class="modal" data-state="open">
<div class="modal-content">
Modal Content
</div>
</div>
CSS
/* Modal container */
.modal {
display: none;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
}
/* Modal content */
.modal-content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: white;
padding: 20px;
animation: fadeIn 0.5s ease-in-out forwards;
}
/* Show modal when state is open */
[data-state="open"] .modal {
display: block;
}
/* Fade-in animation */
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
This modal will fade in when its
data-state
is set to open
.