Cleaner CSS and stylesheets in .NET MVC
31 Jul 2011, 10:28PM
Its after midnight, I'm in a bar somewhere discussing code with another developer. He tells me I need to blog more. I tell him I need to add more features to my website and anyway I need things to blog about. Then I start telling him about a CSS issue I was working on and it got me thinking. So here are my thoughts on it all...
So when I read this it reminded me (and annoyed me) about something I did a while back. One of those ideas you have and think about but do nothing about and years later something kinda different but encompassing that idea is done by someone else. So at least if I blog about them I can point back and say, hey I had that idea first...
So here's a screenshot of a file I've had sitting on my desktop for almost 2 years. It's an idea I had while at a previous work and rather than doing actual work I wrote up the following example css file...
At the time I thought it would require changing the CSS specification but if you look at what LESS has done you can see it can be achieved with plugins doing behind-the-scenes translation. I don't know when LESS was written but I at least had this idea well before I saw Hanselmans post ;)
So theres two (and a half) things that I'm trying to convey here. The first one was using variables in the stylesheet so that commonly used values (like colours) are stored once in the file rather than being repeated throughout. The second was the use of nested CSS selectors. It seemed messy to me to repeat a parent divs id again and again in the CSS file as a prefix for each child element. Why not nest them?
The "and a half" idea was too put an id on each body tag so you could prefix and separate styles on different page types (templates). So for example "homepage" or "general-content" or "sitemap" etc.
Now LESS does this (and presumably more) but by parsing the CSS file and presenting it to you in a tidier way. You then edit and save it and it saves it as a normal CSS file (not what you saw) and uses some special formatting (e.g. indentation to indicate nested selectors) so it can re-read it again when opening it. Ok but it messes up your CSS just a litte.
So since the late night discussion in the pub I've been thinking about how all this fits together with my current work and some of the thoughts I've had around CSS with MVC projects.
I'll continue this in my next post...