The CSSContainer class is used to manage and compose Tailwind CSS classes for various form elements (widgets) and error states. It allows you to define a base set of classes that apply to all elements, and then specialize classes for specific widget types or add/remove classes using set operations.
Key Features:
- Base Classes: Setting a
base key in the input dictionary applies those classes to all supported widget types. - Specialization: Providing specific keys (e.g.,
text, checkbox, error_border) overrides or extends the base classes for those specific elements. - Class Composition: Use the
+ operator to add classes to specific fields and the - operator to remove them. - Automatic Widget Mapping: The
get_input_class method automatically resolves a Django field to its corresponding CSS class string based on its widget type.
from crispy_tailwind.tailwind import CSSContainer
# Initialize with base classes and specific overrides
styles = {
"base": "block w-full rounded-md border-gray-300 shadow-sm",
"text": "focus:border-indigo-500 focus:ring-indigo-500",
"checkbox": "h-4 w-4 rounded border-gray-300 text-indigo-600",
"error_border": "border-red-500"
}
container = CSSContainer(styles)
# Add more classes to specific widgets using +
container + {"text": "extra-padding", "checkbox": "mt-1"}
# Remove classes using -
container - {"text": "extra-padding"}
# Get the class for a specific Django field
# (Assumes 'my_field' is a Django field with a TextInput widget)
class_name = container.get_input_class(my_field)
print(class_name) # Output will include base and text classes