Best practices for structuring CSS code [duplicate] - css

This question already has answers here:
Best way to structure a CSS stylesheet [closed]
(2 answers)
Closed 8 years ago.
I am creating a design for a mid-sized Web application. It's my first time, and there is no established design process at my workplace. Previous projects are small internal applications, and the back-end developer used a minimal design just enough to make stuff align where it should.
I started doing the design for each type of page separately, and created a new CSS file for each type of page, e.g. a separate one for input forms, another one for the search interface, and so on. I also made one large file with elements used everywhere (header, footer, buttons, warning messages and so on). It was the only reasonable structure I could think of.
I've been at it for a while, and I'm now noticing that I've created some sort of chaos. When I have an element and need to change the definition of its style, I always have to go through Inspect Element and then Visual Studio's search function, which is still reasonably efficient. But I also frequently find myself looking at definitions in the stylesheet, having no idea what they are for, or if they're still in use at all - maybe we have already thrown out the elements which use them, or they were an attempt to solve a problem which got a better solution.
I am already trying to give good, semantic names to my classes, but it's not sufficient, and sometimes even impossible - every workaround I use seems to leave me with names like .centeringWrapper.
What is a good, workable structure of CSS code which prevents these problems? What principles can I apply to arranging the code?
How can I divide the code into files so I can find the correct file?
How to structure code inside the files so I can keep my orientation within a file?
How to keep the overview of different definitions for the same element which are used within different #media blocks?
Any advice for making my work less messy is welcome.

The best practice for structuring your CSS is to structure your CSS. By that I mean have a system. It doesn't really matter what your system is, as long as it makes sense to you and your team and people can consistently maintain it (at least for a reasonable length of time).
I can tell you one way not to do it, though and that's by not designing each page separately with its own CSS.
I think you've figured this out already, but it's worth repeating.
Now, there are times when I've broken this rule. But it's rare and it's typically on small marketing-centric sites where I simply have 4 very different pages. In general, though, you want to re-use as much of your CSS as you can across all your pages.
One way to achieve that is to start with a pre-existing structure by working off of a CSS framework. A common one is Bootstrap, but there are literally dozens and dozens of options out there.

Related

CSS File Structure [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Is there any best practices or very practical solutions to organizing mass amounts of css files.
Firstly, how should you use css within a page, should you have a external style sheet for each individual page, and a include css file for 'css reset' and all common elements. Say you have a included header how would you style it, would you have another external style sheet.
This just add up to mass amounts of style sheets, then secondly how to you organize them, do you have a folder for each external style sheet for each page?
Lastly, is there any standard naming conventions, for example if the file was an include would it be 'filename.inc.css' or if it was for a specific page would it be 'filename.pagename.css'
I object to the premise of the question...somewhat. The fact you have so many CSS files speaks to unnecessary bloat. You are probably coupling your styles to a specific context rather than to classes of content. Check out what they are doing at Yahoo for what I mean.
When your CSS is less-context specific, it becomes leaner. This then dramatically reduces the size of your files and mitigates your issue by curing the disease rather than treating the symptom.
So take the time to rethink your CSS to make sure it is only as big as it needs to be. Then organize your layout according just to whatever makes sense for you. After all, the layout of your CSS into multiple files is for your benefit only as a developer. The files will be minified and combined into a single file for the purposes of caching and performance.
And CSS files that are less likely to change because they have been designed for maximum immutability are ideal for caching.
Check http://smacss.com/
SMACSS (pronounced “smacks”) is more style guide than rigid framework.
... SMACSS
is a way to examine your design process and as a way to fit those
rigid frameworks into a flexible thought process. It is an attempt to
document a consistent approach to site development when using CSS.
My advise is always use a preprocessor, it makes the modularity easier. And use SMACSS because is the best way to do CSS especially when dealing with large styles. Check bootstrap repo for an example https://github.com/twbs/bootstrap/tree/master/less
If you have a stylesheet for each page, then every page will have to download a new file. That's definitely not good. You want to take advantage of caching (this goes for anything on the web, not just css) so it would be better to have a little more overhead on a larger css file that only needs to be downloaded once for the whole site. This is a subjective question, however, so there could be and probably are cases where it could be better to split them up - maybe if there were two distinct parts of a site that both needed a massive amount of css.
Generally, having multiple css files is for development only and they should be combined for performance reasons. For example, if I had a menu.css, header.css, etc, those should be in one file when deployed. One example where multiple css files is more acceptable is when they are lazy-loaded by a plugin system like Content Management Systems use. Because the content is so dynamic and the plugins are not tightly coupled to the CMS, it doesn't make sense for all of the css to be combined. That would make it pretty difficult to add and remove plugins.
Oh! In addition to combining all of the css, minification is also great!
There are also libraries like LESS and SASS that are useful in organizing code and cutting down on the amount you need to write.
The best practice would be to have one external style sheet for the entire website. If you can try to name your classes and id's uniquely where they need to be set apart so that there is no confusion between them all in your styling. This way you can maintain the entire site from one file.
If it is absolutely necessary for you to have different style sheets for each page then keep the majority of the styles you will need to render and load that are not page specific and occur on all of the pages to one main css file, then keep the remaining ones that are page specific to a minimum, this will keep your performance higher and save yourself a lot of headaches down the road.
The less technical debt you acquire the better.
Also if you do need multiple style sheets and there are page specific styles you will need that occur on several pages, I would recommend bundling and merging your style sheets to keep the downloads to a minimum and keep your performance higher.

How to organize CSS Sheets [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I would wish to start a discussion to get some good ideas on how to organise style sheets in a very big project with a big team of developers working on it.
One possible approach here is to have just one sheet with all the styles organized using comments and regions, unfortunately even using a one-lined writing approach with tabs this sheet would become incredibly big and even having SVN commits and updates could become messier.
So we think it would be better to divide styles in different sheets. What we are not sure is how to organize this as we have different ideas for it.
One possible idea is to organize it for types: colors.css, fonts.css, forms.css, ...
Another idea is to group them by functionality/behaviour: navigator.css, menu.css, warnings.css, errors.css, ...
We could also organize them by page: login.css, contact.css, home.css, ...
Or even use a combination of those three ideas together.
Now what worries me is the fact that we would prefer not to add all the styles to every page, as not all the pages require all the styles and we are really worried about performance as our project is consumed by millions of users everyday. We of course compress it later on deploying but even so we think it's wiser to load only the required ones per page.
On being so, I am worried about other developers not loading styles in correct order, as having different sheets needed to be loaded depending on the page, or on the group of pages, they could get this messed up and on doing so cascading will fail (imagine they load menu.css before global.css, global would override some menu styles!!!).
Now we could just go for one sheet, we could just load all of them always, or we could use some idea we came to like using an alphabetical prefix to tell developers the loading order:
a_global.css
a_forms.css
b_region1.css
b_anotherregion.css
c_page.css
But that looks a bit horrible being honest. So now I was wondering if there is some type of popular css architecturing out there or at least some good ideas we could use for our project here.
Many Thanks!!
Go with a preprocessor, so you can organize source files however you want. (Our team uses LESS, because we've started with Twitter Bootsrap and it stuck). The compiled CSS file should not be under version control, each developer should compile their own version for testing. I'd recommend a grunt task to compile a minified version for production. I'd go with component-centric approach (forms, navs, grid, typography etc).
Using a preprocessor gives you the power of variables and mixins. You can keep files like variables.less and mixins.less in which you define common styles. So you when that blue color changes into slightly lighter blue you just change it in one file.
One large file including all the CSS you need should be fine as it is cached by browsers, so it minimizes HTTP requests to your serwver. Page-specific stylesheets are OK when a particular page has many uncommon elements.
Create a style guide html template which includes every common element you can think of. Headings, link colors, lists, photo thumbnails, form inputs, grid configurations, accordions etc. When you need to create a new component add it to this template, modify the stylesheets, see if it breaks any other elements and how it fits with the rest. Then use these snippets to create particular pages.
SASS or LESS
This will help you to keep your code easy managed. (variables, mixins etc)
Divide in multiple count of files.
Always a good idea. How to divide.
I suggest basically to divide them per page.
BUT -
Exclude general styles to seperate files which will be included everywhere.
By the way, one single file doesn't imply low performance. Are you sure that 10 requests for smaller sheets will be faster than one request for bigger file?
Additionally this files will be cached in web browser, so one file doesn't look like a bad idea.

Is it that wrong to use table instead of css' float?

I've made websites before it was really used, and I've made the decision years ago to use CSS to design my webpages. It was a lot of trouble to leave the great tables and try "clearing both" instead.
The question is, after all those years I still have trouble sometimes. And everytime I run into a bad CSS situation I recall the easy way to make cols with "table".
And the more I'm thinking about it, and the less I understand why we dropped the use of table. They are great to design pages, and not every websites need to be 100% W3C conform or have hundreds of page that wouldn't support a change of design because of that.
So yeah, now I'm thinking about going back using tables. Should I do it? Do pro designers actually use tables where they shouldn't use them?
I also stumbled into a grotesque table in the google map API. If google ingeneers are taking that shortcut, why not me?
(sorry for my english I'm not fluent).
EDIT:
lot of response says it's my fault. I considered being pretty good in CSS, started with books of Eric Meyer and have been doing CSS since 2005. I know that the trick width:100%;overflow:auto; works in most case (and also that we didn't have this trick bad then), but I wonder if it would be a bad thing to use tables to quickly do the job on smalls website, like a blog.
I had the same issues when I started dropping tables and using CSS. Sometimes CSS floats can be a pain, there are a few tricky edge-cases that come up when using them for page layout, but you'll learn how to deal with them and it really is worth it. Your code will be 10% of the size and much easier to work with.
Another consideration is CSS floats can be made to work nicely with mobile devices and small screens. Tables can cause real issues with this, especially if you want to add nice touchscreen improvements.
Lots of "pro" designers use tables when they shouldn't. All over the place. But "pro" is often not the same as "good". Tables should only be used for visible tables of data.
Tables still have an important and semantically correct correct usage. That is for the display of tabular data. That is especially useful in envirnments that are DB-centric or that are process a lot of xml with ajax. For general layout they are not appropriate because the cause slow page loading because the browser has to wait for all contents before it can start rendering. CSS should not be difficult. If you are having trouble you should look at how it is being used on sites where you like the design.
The big advantage of CSS is that you can develop a master stylesheet for a site, and then where individual pages need slight variations you can apply overrides or modifications to specific elements without having to change the master sheet.
avoiding table layouts offers up a plethora of benefits but # the end of the day, browsers are still entirely too forgiving (currently) and you can get away with it. if you are wary of going back to them, read up on display:table and css3. it's practically table based layouts, minus the table.
One reason tables are avoided is that the content inside of them does not display until the HTML for the entire table has loaded. With the CSS method, this is not true.
If you really have a lot of trouble with the CSS method, you must be doing it wrong. Consider reading over other people's code to see how to do it better.
6 years later (we're now in 2017) and CSS now has grids and flexbox which should be the easiest way to build a layout without using ugly hacks and without using tables.

How to manage css of big websites within team environment without mess?

Where multiple people can work on same css. is it possible to follow semantic name rules even in large websites.
If I would write all main css first time with semantic names . then what and how i should guideline/instruction to other developer to maintain css readability, validation . and to know quickly where other are adding their own css if required.
Right now every one just go to down and write required css classes ot IDs at bottom. and most of the time they don't write semantic names.
How to make good documentation/guide with text or with images for other developers on how to use css in whole site and how i wrote and what i used.
Update:
We use only one CSS file. I don't want to divide one css in multiple. Want to keep css managable even using one CSS file for whole site.
A similar question was asked a while ago: How to manage CSS Explosion there is a number of good answers there, and a number of great links (check out those provided by Paul D. Waite for example.)
Your main problem is going to be structuring the CSS file well. You will need clean rules for that: Keep everything grouped within the CSS file. Maybe using a CSS editor that can help you "navigate" through the style sheet is a good idea (similar to a programming IDE's "code explorer" feature). I don't know, however, if such a thing exists.
Other than that:
Using version control is a MUST. I personally am totally happy with centralized versioning using Subversion and TortoiseSVN; others believe in distributed version control like git or hg. For a team of designers, I think the centralized approach of Subversion is good, but that is a discussion in itself.
Maybe it's a good idea to split the style sheet into thematically relevant separate files to avoid chaos, and compile it using a tool like LESS or xCSS.
Define a clear, concise coding style. Use a CSS beautifier like Polystyle ($14 per license but money well spent) or Code Beautifier (based on CSS Tidy, haven't used it but looks interesting) and run it frequently on the file.
Have a number of links handy of pages that use the style sheet. Have people test those pages after they have made a change to the style sheet.
I would break down your css logically into groups and put each of these groups into its own css file. For example: header, footer, sidebar, content groups. Maybe some pages even deserve their own css file if big enough.
Similarly, give ids and classes on pages names that make sense. If it is a css rule for sub headings on a navigation bar, make sure it comes off as that in naming. Similarly to any other coding, don't use any magic numbers, etc. for naming.
See Modularizing web applications, includes specially CSS

How to implement a "news" section in asp.net website?

I'm implementing "news" section in asp.net website. There is a list of short versions of articles on one page and when you click one of the links it redirects you to a page with a full article. The problem is that the article's text on the second page will come from database but the articles may vary - some may have links, some may have an image or a set of images, may be differently formatted etc. The obvious solution that my friend have come up with is to keep the article in the database as html including all links, images, formatting, etc. Then it would be simply displayed on the second page. I feel this is not a good solution as if, for example, we decide to change the css class of some div inside this html (let's say it is used in all articles), we will have to find it and change in every single record of the articles table in our database. But on the other hand we have no idea how to do it differently. My question is: how do you usually handle something like this?
I personally don't like the idea of storing full html in the database. Here's an attempt at solving the problem.
Don't go for a potentially infinite number of layouts. Yes all articles may be different but if you stick to a few good layouts then you're going to save yourself a lot of hassle. These layouts can be stored as templates e.g ArticleWithImagesAtTheBottom, ArticleWithImagesOnLeft etc
This way, your headache is less as you can easily change the templates. I guess you could also argue then that the site has some consistency in layout.
Then for storage you have at least 2 options:
Use the model-per-view approach and have eg ArticleWithImagesAtTheBottomModel which would have properties like 1stparagraph, 2ndparagraph, MainImage, ExtraImages
Parse the article according to the template you want to use. e.g look for a paragraph break if you need to.
Always keep the images separate and reference them in another column/table in the db. That gives you most freedom.
By the way, option #2 would be slower as you'd have to parse on the fly each time. I like the model-per-view approach.
Essentially I guess I'm trying to say beware of making things to complicated. An infinite number of layout means an infinite number of potential problems. You can always add more templates as you go if you really want to expand, but you're probably best off starting with say 3 or 4 layouts.
EDITED FROM THIS POINT:
Actually, thinking about it this may not be the best solution. It could work depending on your needs, but I was wondering how the big sites do it. If you really need that much flexibility, you could (as I think was sort of suggested) use a custom markup. Maybe even a simplified or full wiki markup. I'd still tend toward using templates in general, but if you need to insert at least links and images then you can parse for those.
Surely the point of storing HTML with logically placed < div >s is that you DON'T have to go through every bit of HTML you store to make changes to styles?
I presume you're not using inline styles in your stored HTML, and are referencing an external CSS file, right?
The objection you raise to your colleague's proposal does not say anything about the use of a DB. A DB as opposed to what: files? Then it's all the same. You want to screw around with the HTML, you have to do it on "every single record." Which is not any harder than "on every single file." Global changes are a bitch unless you plan for it by, say, referencing an external CSS. But if you're going to have millions of news articles, you had better plan on versioning the CSS as well.
Anyway, the CMSes do what you're thinking of doing. Using a DB is a fine way to go. How to use it would depend on knowing the problem more intimately.
Have you looked into using free content management systems? I can think of a few good ones:
Joomla
Drupal
WordPress
TONS of others... just do some googling.
Check out this Wiki article: http://en.wikipedia.org/wiki/List_of_content_management_systems

Resources