Css Best Practice Dilemma - specific case - css

A client asks for an admin table and one column will have different cell colors based on some rules.
My problem is : what is the best css practice for this.
we know inline is bad from the start
we could do some css classes for each color and give them a good name but this will just clutter then main css file with classes that will probably never be used again.
So what would be a good approach for this simple problem ?

So what would be a good approach for this simple problem ?
You have essentially already outlined your two options. It's your choice.
I would always go with classes, and never with inline CSS. If you're worried about cluttering, you could add some order using comments:
/** Table highlight styles **/
table.data td.highlight { background-color: #CCCCCC }
table.data td.total { background-color: #ABCDEF }
You could theoretically put these into a separate CSS file, but the number of style sheets should be kept as low as possible. To do this right, you could use a CSS preprocessor as suggested by #Ian.... but that is an entirely different and new can of worms.

Personally, I would recommend using something like dotless(DotNet) or less (Ruby).
Here you can define a colour like #MyMainColour and then have div.SomeBackground { background: #MyMainColour; }
These tools will allow you to "compile" your CSS compress and turn out customer specific themes.

You might consider:
Keep a separate css file for specific adjustments. This might be a good compromise between keeping a main style file uncluttered, but still be able to target specific GUIs with adjustments.
Let a GUI have an id. This way you can let GUI specific adjustments only affect that GUI with styles given in context.

Related

Using nth-child or creating new classes in CSS?

I've just started my first project which is building an admin panel. My task is to create HTML and CSS - sort of a base of design to process further to the back-end developers.
I was asked to keep CSS simple and classes as descriptive as possible ( could be long ) and to use Bootstrap.
To avoid creating unnecessary classes which could be used once or twice I decided to go with :nth-child since I thought giving new class to each column is too much. Additionally I created few base classes that might be used for adding 0px padding and margin.
Unfortunately, as I was writing more and more code I've noticed that some CSS code looks like this:
.print-history-advanced-search > [class*='col-']:nth-child(5) > .form-group > .form-horizontal > .form-group > [class*='col-']:first-child
And it is not a single line.
Additionally, I've noticed that sometimes that when I am making a new class and it has lots of parent elements, I cannot write the CSS selector by its own, but I need to state the parents of the this particular element and put the class at the end, which does not make sense.
Is there any solution I could use to avoid creating classes that are simply used in one or two divs, but also make the CSS code less chaotic and avoid very long names? Or maybe I should just give up on children and nesting and work with just classes?
Thank you for your help!
Have a nice day!
If you want to write good CSS, then I'd suggest the BEM model is a good route to go down.
The essentials are;
No element/selector heirachy
No use of elements in selectors
Class based styles only
BEM stands for Block, Element, Modifier - which is how your class names are formed. Borrowing an example from their site;
.form { }
.form--theme-xmas { }
.form--simple { }
.form__input { }
.form__submit { }
.form__submit--disabled { }
<form class="form form--theme-xmas form--simple">
<input class="form__input" type="text" />
<input
class="form__submit form__submit--disabled"
type="submit" />
</form>
You can see there's a form Block, and then a form__input and form__submit Element, and then a form__submit--disabled Modifier.
Depending on your needs I would recommend using css preprocessors like SASS,LESS.
You’ll find that as a website grows, you’ll develop a pretty long, scrolling list of various elements and CSS rules. Some of the rules might overlap or override each other eventually (in that case, usually the more specific rule will win).
You can end up with a lot more code than you expected, especially considering the different variations of a rule you need for different browsers and screen sizes.
There are many ways to refactor your CSS code to make it easier to navigate and use. Some of the easiest methods are the most effective and have the most mileage. Here are some of the quickest ones:
Keep your spacing uniform: Maintain the same spacing between rules
and within declarations throughout your file so that it’s easier to
read.
Use semantic or “familiar” class/id names: Instead of using a class
name like “bottom_menu”, try using the semantic tag “footer”. Or
when you have an image in your “contact” section, make sure you’re
using a class on your image like “contact_image”
Keep it DRY (Don’t Repeat Yourself): Ideally you want to repeat as
little of your code as possible. Do you find the declaration
“background-color: #000″ repeated throughout your CSS file? Consider
typing it once and instead, using multiple selectors on the one
declaration.
Put your tidiness to the test with these tools: Run your CSS through
CSS Lint or W3C—these will help to parse your CSS file correctly,
and highlight problem areas. Your web browser’s developer tools are
also extremely useful for pinpointing specific elements on your
website and using the area as a sandbox to experiment with different
styles and positioning.
Have a look here for more info

GWT Widget development: combining & overriding CSS

I've just started learning GWT so my question might be noobish. Tried to find a 'standard' solution but couldn't find it.
I'm developing an AddressWidget. It is implemented as a Composite widget which consist of atomic widgets (Labels, TextBoxes, ListBoxes...) defined in AddressWidget.ui.xml. These tiny building blocks should get their CSS from the common-widgets.css. The AddressWidget itself should get the default styles from address-widget.css.
As this widget will be used on different pages, they should be able to override the styles applied in order to customize the appearance. I.e. the OrderPage should apply its own from the order-page-address-widget.css, the ContactDetailsPage – from the contact-details-address-widget.css
How do I implement that?
My advice - drop this idea. It will be hell to develop and maintain, and I mean it. You will constantly try to figure out which CSS file has to be updated, and then you will have to test every update in multiple places, because an update in one file can mess up with CSS from another file.
Many GWT developers prefer to use CssResource approach to CSS. I've never heard any designer favoring this solution, though.
After years of working with GWT on both the code and design sides, I strongly prefer to use a single CSS file for the entire application. CSS was built for inheritance, and this is what a single file achieves. You can define basic style, like:
input {
height: 24px;
}
If you need to change these styles in specific widgets or parts of the application, you can set, for example, "contacts" class on the contacts page/widget, and then add this to your CSS file:
.contacts input {
background: grey;
}
The advatantages of this approach:
easier to enforce consistent look throughout the application
easier to maintain your CSS, because there is one file to update, and there are no conflicts with CSS defined anywhere else
it is an approach that most designers understand and know how to use
it is the easiest solution if you want to create multiple skins or themes for your application
it is easy to make your CSS adjust to different screen sizes, or define special styles for printing.

Confusion with BEM modifiers

I have started using BEM methodology while writing my CSS and there have been few occasions where I have struggled to find out the best way to do a particular thing.
I would like to take up a simple example of a panel here.
Lets say I am writing a panel component CSS using BEM style. So my CSS might look as follows:
.panel {}
.panel__titlebar {}
.panel__content { display: none; }
A panel can be either chromeless or with chrome. So I define another modifier class for the panel:
.panel--with-chrome {
border: 4px solid black;
border-radius: 4px;
}
Now lets say, the panel can be in a fullscreen/maximized state also in which the chrome and titlebar disappear. Instead of defining modifiers for both panel and titlebar, it would be be wise to define the modifier just on parent (say panel--fullscreen) and rest elements shall change accordingly. So now my CSS becomes:
.panel--fullscreen {
/* something has to be done here */
}
.panel--fullscreen .panel__titlebar { display: none; }
To remove the chrome in fullscreen mode, I can either:
toggle the panel--with-chrome class in JS along with the panel--fullscreen class
overwrite the chrome CSS inside the panel--fullscreen class.
First isn't good because ideally I would like to simply toggle just one class (.panel--fullscreen) in JS to toggle fullscreen mode.
And second one is bad because I'll have to overwrite previous CSS which is a bad practice.
So whats the best way to go about it? Appreciate your comments.
Thanks
The answer depends on many things.
First, how much logic and appearance have "panel--with-chrome" and "panel--fullscreen" modifiers. And also on what kind this logic is.
If "panel--with-chrome" brings a lot of CSS properties and special JS functionality, I would toggle it in JavaScript when applying "panel--fullscreen".
It also depends on a JavaScript framework you use. In "i-bem.js" which we use at Yandex it's easy to react to appending a modifier:
A square changes size modifier when after a click
Reacting on applying a modifier
But if the framework you use doesn't allow to express such a reaction handy, this answer won't work that great for you.
In the other case, when "panel--with-chrome" has not very much properties and doesn't bring any JavaScript logic to a page, I would redefine those CSS properties in "panel--fullscreen" class.
To sum up, there is no universal solution and strict rules to follow. You should decide yourself what will be useful in your case. The decision should depend on many things:
if you expect your project to be maintained in the future, which solution will be easier to support?
capabilities of the JavaScript framework you use
performance stuff
Not in this particular case, but sometimes we measure speed of rendering for variants we are choosing from.
opinion of the other guys, if you work in team
file structure of your project
We, here at Yandex, store CSS and JavaScript for a block in the same block folder. So, it is not a problem to share logic between CSS and JavaScript since they all are in one place.
But if you keep your JavaScript files separately, this can influence on how comfortable it is to support shared logic.
And so on...
I’d go with the first option; you are toggling state after all, so you need to add/remove/toggle classes accordingly. It’s better than undoing a load of stuff in CSS IMO.

How to remove CSS spaghetti in legacy web app?

After working on several large web applications, and seeing gigantic style sheets with no clear structure, I'd really love to know if people have found ways to keep their css clean for large and complicated web apps.
How do you move from a legacy, mess of css to cleaned up, nicely cascading, DRY stylesheets?
The app I'm currently working on has 12000 lines of css. It's grown to this size organically as early on there were no standards or review of the css, the only rule was to make the app match the design. Some of the problems we constantly have:
Conflicting styles: one developer adds a .header { font-weight: bold;} but .header was already used in other modules and shouldn't be bold in those.
Cascading problems: Foo widget has a .header but it also contains a list of Bar widgets with .header classes.
If we define .foo .header { ... } and .bar .header { ... } anything not explicitly overwritten in foo will show up in bar.
If we define .foo > .header and .bar > .header but later need to modify foo to wrap header in a div, our styles break.
Inheritance problems, we constantly redefine widget fonts to 11px/normal because some top container uses a 12px / 18 px line height.
Fighting against widget libraries, using libraries such as dojo/dijit or jquery ui that add tons of styles to be functional means that our code is littered with places where we have to override the library styles to get things looking just right. There are ~2000 lines of css just for tweaking the builtin dijit styles
We're at a point where we're thinking of implementing the following rules:
Namespace all new widget classes - if you have a widget foo all sub-classnames will be .foo_ so we get: .foo, .foo_header, .foo_content, .foo_footer. This makes our css essentially FLAT, but we see no other way to organize our code going forward without running into the legacy styles or the cascading problems I mentioned above.
Police generic styles - have a small handful of generic classes that are only to be applied in very specific situations. e.g. .editable - apply to portions of a sentence that should invoke an editor - should only contain text nodes.
Leverage css compiler mixins To avoid repeatedly defining the same styles in different widgets, define and use mixins. Although we worry the mixins will get out of control too.
How else can we move from css mess that constantly introduces regressions to something maintainable going forward.
We're using a style guide in the form of a simple HTML page with examples of every CSS rule in the stylesheet. It's very easy to tell if you add a new, incompatible rule since the examples are aligned on top of eachother.
An example I like: http://getbootstrap.com/components/ (added 2015)
The other pro you get from this method is reusability: you know what you got and you know that you want the style guide to be as small as possible - therefore: reuse.
When you make changes to styles already in use: check the style guide. If it doesn't change it's probably good (you might need to browse around a bit if you've just changed something including box model-issues, or width, height, padding, margin in general).
How do you move from a legacy, mess of
css to cleaned up, nicely cascading,
DRY stylesheets?
Use the style guide as a unit test. Once you got the essential parts in it: reduce, refactor and combine (you most probably will find some collissions between .campaign_1 span and your regular rules, inheritance can be your friend).
Conflicting styles: one developer adds
a .header { font-weight: bold;} but
.header was already used in other
modules and shouldn't be bold in
those.
In reply to Adriano Varoli Piazza's comment and the quote above: I don't recall this as a problem fully belonging to the CSS but more to the HTML markup. No matter what you do, it will be some heavy lifting. Decide which rule you'd want to keep and take actions towards cleaning out the lesser-used-ones; for example: via inheritance: #news a .header { ... } or renaming the HTML-class a .stand_out_header { ... }.
About the following idea
Namespace all new widget classes - if
you have a widget foo all
sub-classnames will be .foo_ so we
get: .foo, .foo_header, .foo_content,
.foo_footer. This makes our css
essentially FLAT, but we see no other
way to organize our code going forward
without running into the legacy styles
or the cascading problems I mentioned
above.
Use a containing element instead, which will be much more easy to maintain:
<div id="widget_email">
<h2>One type of h2</h2>
</div>
<div id="widget_twitter">
<h2>Another h2</h2>
</div>
I find that the method for "namespacing" and limiting conflict in CSS is separate into different includes what you want to apply, so each page calls only what it needs. Conflicting rules can then be made more specific simply by defining them in a more particular include:
general css for all pages
css for pages in section A
css for pages in section B
So if you find a .header modification you added in the general css works in A but doesn't in B, you simply move it to the lower CSS file.
Yes, this implies more files to load. There are ways around it with server-side languages, like reading all files with php and sending only one block of content.

CSS coding style [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Are there any good CSS coding style/standards?
Here is a good one:
http://www.phpied.com/css-coding-conventions/
But the important thing is to pick something and stick with it for consistency.
I agree with most of the points at Andrew Hare's link, but I strongly believe
.class-name {
color: green;
}
is inferior to:
.class-name
{
color: green;
}
on the grounds that:
.class-name, .class-name2 {
color: green;
}
or:
.class-name,
.class-name2 {
color: green;
}
are considerably less obvious to grep or read than:
.class-name,
.class-name2
{
color: green;
}
There's no standard standard, as it were. There are most certainly plenty of in-house standards and conventions. And there are certainly known best practices.
I stick to the following:
Structure your CSS according to it's purpose
That may involve separating out CSS concerns into different files (layout.css, colors.css etc). This may just as well involve clearly dividing up a single CSS file into clear sections along the same lines.
Be as specific as possible
Selectors have differing weights. ID-based selectors are more specific than class-based selectors. Chained selectors (e.g. body div#container div#content p) are very specific indeed.
Start out being as specific as you can, even if it appears you're being too specific. It's quite easy, later down the line, to merge together two very specific style definitions by removing one and making the other less specific.
A style definition with loose specificity may target elements you did not intend in ways that are not immediately apparent or obvious. I think this is the most common cause of CSS frustrations ("Why on earth will this div not let me set a top margin?")
Always specify every single style you wish to apply for a given defintion
For example, if you want all your paragraphs to have pink text, set the text colour to pink and also set the margins/padding/background colour/font and so on.
Don't rely on browser defaults to be suitably consistent. Certainly for the most commonly used elements the main browsers tend to use very similar if not identical default styling.
If you set all the relevant styles yourself you know what the end result should be.
If you only set those styles that are most immediately obvious, the end result will be (most likely) a combination of the browser defaults and your styles. This will eventually catch you out at some point. I think this is the second most common cause of CSS frustrations.
Use ids for styling unique elements
It's generally a good idea to apply an id attribute to any unique element that is going to be interacted with in any way. For CSS this will let you apply suitably specific styles more easily.
Use an id on a unique page
Pages that are significantly different in style and layout to the majority (homepage, search results, 404) should have an id on the body element. This gives you the specificity you need to ensure that your careful homepage styling doesn't get affected by styles you later apply to some internal content page.
Pretty coding style VS site speed
I've been working with pretty huge CSS files, and found out some pretty interesting things that I've never read about before.
#import
One thing is using #import. That's actually a bottleneck - by going away from using #import completely, the site got a lot more snappy.
#every .style { in one line }
When the browser reads a document, it reads line by line, so by switching from my pretty coding style to this, I accomplished 2 things;
A even more snappy site
Less scrolling, better overview. Why? Cause I first scroll down to find the style I'm going to work with, then it's all in the same line and it's not hard to scroll your eyes along the line to find what you're looking for.
The main good coding style is to actually separate css files according to their goals.
See Progressive Enhancement.
That way, whatever coding convention you will choose, you will have consistent and manageable separate css files... easier to debug.
When I code in CSS:
In first part I write the class and id
In last part I write the general element (p, font, etc) because the class and id have more importance for inheritance
I write comment if I want a particular behaviour with IE or with MoSE Browser
You can see some example in CSS Zen Garden
Generally I insert the most important elements over the other: if there's
p.important{/*features of a class*/}
p {/*features of a general element */}
Reading the CSS file I know the format rules before about the most particular elements, after the rules about the most general elements.
It's an habit in programming Java.
Put your css rules (ex: "color: red;") in alphabetical order and also put your selectors (ex: "div { color: red; }") in order they appear in your markup. Separate code for structure from skin.
Just from experience I used to write quite long CSS style sheets. Now my style sheets typically are half a page.
So keep it simple(KISS), line based (greppable) and keep it compact (use font: instead of font-size etc etc.).
Also I highly recommend using CSSlint to check your code for fluff.
Check Sass out. It's a template language for CSS that makes your source code DRY:er and mucho easy to read. Even if you're not using ruby you can use it for this task and automate the building of your css files from Sass source. And there are probably Sass implementations in other languages too.
There's probably loads. At our work we use the following:
/* =div a comment about my div */
div#mydiv {
border:1px solid #000;
}
The =div allows us to search against all div elements by using the search functionality. There's loads more though, I've used many different variations of this in the past.
In addition to what others said, remember that the C stands for 'Cascading', i.e. subelements inherit from top level elements. Sound simple and straight away. But I have often seen CSS files that contain redundant declarations, e.g. for font styles. This makes a CSS more complex and hard to maintain.
So before you add something to your CSS make sure that it is not redundant, i.e. check parent elements and remove redundant declarations from children.
Given this you should organize your CSS in a way so that high level elements (like declarations for the body class) are mentioned first and more specialized elements last.
This might also be helpful, a few tips to keep your CSS styles DRY - as in "Don't Repeat Yourself" link text
I will strongly recommend looking at Less: http://lesscss.org
While not really a standard, it has been gaining a lot of momentum recently. Less is css extension that runs in the browser bringing variables and functions into the language and therefore allowing templating.

Resources