audrey.feldroy.com

The experimental notebooks of Audrey M. Roy Greenfeld. This website and all its notebooks are open-source at github.com/audreyfeldroy/audrey.feldroy.com


# Accessing CSS Classes in FastHTML

by Audrey M. Roy Greenfeld | Fri, May 9, 2025

How to retrieve the CSS classes for a FastHTML FastTag instance.


from fasthtml.common import *

Define a Div in FastHTML, With Tailwind Classes

Here's a typical div with several Tailwind CSS classes:

d = Div(cls="container mx-auto p-4 bg-white dark:bg-gray-800")
d

<div class="container mx-auto p-4 bg-white dark:bg-gray-800"></div>



div((),{'class': 'container mx-auto p-4 bg-white dark:bg-gray-800'})

Get the CSS Classes

The FT variable d has these attrs:

d.attrs
{'class': 'container mx-auto p-4 bg-white dark:bg-gray-800'}

To get the CSS classes, you get the class attribute of d:

d.attrs['class']
'container mx-auto p-4 bg-white dark:bg-gray-800'

Parse Them Into a List

Then you can split the space-separated string into a list, if you like:

css_classes = d.attrs['class'].split()
css_classes
['container', 'mx-auto', 'p-4', 'bg-white', 'dark:bg-gray-800']

© 2024-2025 Audrey M. Roy Greenfeld