Wednesday, September 10, 2008

Override any CSS style (even inline styles) no matter where it is defined

Cascading Style Sheets (CSS) are very nice for formatting HTML. In general, I think it is a very bad idea for an ASP.NET control to emit inline styles because it prevents the developer from overriding the formatting. This is of course unless there is a corresponding property or programmatic way provided of changing it.

The ASP.NET GridView is a great example of this. It emits the following inline style for the table tag it emits.

style="border-collapse:collapse"

If I want to change that *they* provide no way to do so.

However, CSS does provide a way to that I recently found here http://home.tampabay.rr.com/bmerkey/cheatsheet.htm.

So, all I have to do is create a CSS class called something like GridViewStyle by including the following between the head tags on the .aspx page.

<style>
.GridViewStyle { border-collapse:separate ! important; }
</style>

This is the key to this entire solution. Notice the ! important; This means that border-collapse will be set to separate even if the inline style says differently. This is *very* powerful.

To apply this CSS class to the table tag that is emitted by the GridView all we have to do is set the CssClass property of the GridView to GridViewStyle.

12 comments:

Anonymous said...

That was a very useful tip indeed, so I want to thank you very much for your expertise.

Brent V said...

yereverluinunclebert,

Cute user name. :) Thank you for the kind feedback. It is greatly appreciated. I am glad you found it useful.

Thanks,

Brent

Anonymous said...

dammit that is nice!!
so simple and it works!
Thanks :D

Anonymous said...

thanks... solved my problem...

Brent V said...

Anonymous,

Thanks for the feedback. I'm glad it solved your problem.

Brent

Anonymous said...

wow thanks! Have been trying to solve my problem for over an hour, this simple thing did the trick!

acarus-siro said...

Thanks a lot!

Anonymous said...

Thanks for the great tip. i was trying to figure it out for over an hour.

kubilay said...

I needed to override padding-left in my buttons for icons like update, delete, insert... Works great, thank you very much.

Anonymous said...

Thank you sir ! You're a genius, it solved all my problems !!!

Unknown said...

thank you very much its solved my problem

Unknown said...

thank you very much its solved my problem