How to reference a component to apply custom CSS

Hi there,

I am trying to apply a custom style to a link and I notice that there is no way to specify custom CSS beyond properties exposed or a way to reference it in CSS using a selector (E.g. reference the ID).

What is the best way to reference a component for custom styling?

Thanks
SS

Try Anvil Roles.

Docs here:
https://anvil.works/docs/client/themes-and-styling

Clone app:
https://anvil.works/build#clone:XJ3UMT7S77FHW3MU=QWBWPALKR6AZFFNX245VGBJE

You will want to create a new role and give it a name. As you can see below, I’ve called it “link_role”:

Then, in your theme.css (under “Assets”) you can reference that role by prepending “.anvil-role-” to your role name. For this example you would use .anvil-role-link_role. Add the rest of your desired CSS styling, assign the new role to your link in the IDE, and you’re good to go!

Here is the CSS in my theme.css that is associated with my new role:

.anvil-role-link_role:hover {
  color: hotpink;
}

In the designer, I’ve set my link to my new role:

I hope this helps!

2 Likes

If you’re coming from a css world you’ll probably have to tweak your thinking.

You’ll want to explore anvil-roles which adds a class to components. (I couldn’t quickly find much documentation on it but the forum has plenty of examples)

Unlike css a component can’t have multiple roles which is where the tweaking your thinking comes into play

Edit: too quick for me @alcampopiano :slight_smile:

3 Likes

Thank you @alcampopiano @stucork

It appears Roles is the way to go here but I was wondering if this would result in a runaway list of Roles just to style various components within my solution?

Would be nice if there is a way to associate an ID or custom Class Name against a component upon which we can then write custom CSS.

Possibly. But for most individual components, where in css you would use the element id to style, you can just style it once in the design view using the item properties.

Roles are best if you have components that you reuse a lot.

And if you’re not a fan of some of the material design css choices you can use the theme.css and adapt the css as you need

1 Like

@singh, @stucork

I think you can actually have multiple roles for a component. I just found out.

6 Likes

Who knew… :exploding_head:. Definitely a useful feature.

1 Like

I use roles a lot – but I still wish that the component’s name property was added as either the element’s id, or as a class on the element (ie "anvil-element-name-XYZ). Would be super useful for more advanced tweaking for individual components where the desired properties aren’t exposed in the IDE.

3 Likes