i feel like this may be simple enough and I'm just missing it. I recently went to 7-1 folder structure instead of a single scss file. What i'm having difficulty with is referencing .panel(or h2 or span) in _typography.scss to do font-styling and reference the same .panel(h2,span, etc) in my _layout.scss.
I understand from a CSS pov this wouldn't be logical to have them broken up as of sequencing, however, from a sass pov, I feel like there should be a way to structure this so my CSS doesn't have .nav-container mentioned twice.
Just to note, I'm using NPM, not an ide compiler. Maybe I'm just going about structuring generally incorrect and shouldn't separate them.
Please advise,
UPDATE ANSWER
I've marked Frish's answer here correct because the way that they set it up is correct, but after several and i mean several days of research, i've decided to add some context as I see many others have created simiar threads.
The way I initially looked at SASS was incorrect. I was trying to make SASS work in a way i thought would eliminate complexity: (having .nav-container {} typography rules in a typography partial, then .nav-container {} layout in a layout partial.) This isn't the right way of thinking.
The real benefits are all the built in functions (placeholders,mixins, extends) that drive the magic of making SASS more effective.
However, there is a way to still do what you're looking to do, styling selectors across different partials, for example, separating typography styling from layout styling, and so forth, for particular selector. This was a major wakeup call. Passing Style Blocks (or Content Blocks) to a mixin or whatever. So for example:
#mixin button {
font-size: 1em;
padding: 0.5em 1.0em;
text-decoration: none;
color: #fff;
#content;
}
.button-green {
#include button {
background: green
}
}
Finally,
this link(https://openclassrooms.com/en/courses/5625786-produce-maintainable-css-with-sass/5951856-write-cleaner-code-with-sass-extensions) is where it really clicked for me
Look at the section paragraph that starts with "extensions are a lot like mixins." Review this example as it should be easy to apply its setup and way of structuring to what you're trying to do.
Getting deeper into this, i did some googling on "passing style blocks" and "sass passing content blocks" and that helped a ton on how to leverage placeholders, mixins, and extends effectively while still maintaining the simplicity of sass structuring.
This isn't a concrete answer as there are many ways to approach this (as you are undoubtedly aware), but here are my thoughts.
I typically use generic stylesheets (_typography, _layout) for generic elements (h1,h2,h3, .section, .container perhaps). Any element that merits special mention in multiple files potentially merits being its own component (e.g. panel.scss).
This does increase the numbers of folders and files floating around, but I still find this preferable to one, or a few, big files. I usually end up with a main.scss file that looks like this:
// main.scss
#import "_variables.scss";
#import "_typography.scss";
// etc....
#import "./components/panel.scss";
#import "./components/navContainer.scss"; // or, nav-container.scss!
// etc....
Components happily override generic styles, and I can track their CSS in individual files. Happy dev! You can sub-divide components or other files as you see fit.
Related
This question already has an answer here:
Is there a SASS rule for outputting a descendant to the root?
(1 answer)
Closed 6 years ago.
For example, I want to make my code easier to read by doing this:
#article{
...
#article_inner{
...
}
}
However, I want it to compile into this:
#article{
...
}
#article_inner{
...
}
Is this possible using SASS?
Yes, #at-root will do what you want.
However, I question the premise of your question.
First, let's assume you really want to write #article { #article-inner {. For this, SASS will generate the code #article #article-inner {. You want it to generate #article-inner {. But why? Presumably you are concerned about the possibly lower efficiency of parsing, downloading, or applying the former as compared to the latter. Actually, though, any differences in efficiency would be miniscule to non-existent.
Second, I wonder why you think nesting the rules is "easier to read". Actually, to me it's harder to read. Presumably you think following the structure of the HTML is going to make it easier to read. Actually, following the structure of the HTML makes your CSS brittle. In computer science terms, this is called "coupling", generally considered a Bad Thing; in this case, you are coupling your HTML too tightly to your CSS. For instance, if for whatever reason #article-inner moved, or appeared somewhere else, then, even though the ID matched, your rule would stop working.
Experienced SCSS coders make very light use of its nesting capabilities. Instead, they write rules that are orthogonal to the HTML, which can be combined to create a number of styling effects, without being slavisly bound to the hierarchical structure of the HTML. Good SCSS coders I know limit themselves to nesting in the case of things like .class { color: red; &:hover { color: blue; } }, or in other cases to one level at most. In your case, if you have to use #at-root to do what you want, you have now actually made your code less readable in the name of readability.
SCSS is not going to live forever. Some day CSS will handle much of what it now does for us, including variables. Some shops are already moving away from SASS, with its ugly, verbose macros, mixins, hard-to-maintain features like #extend, and excessive nesting, back to raw CSS or forward to more modern preprocessors like suitCSS. We need SASS less and less for vendor-prefixing; other preprocessors support modularized, automated vendor prefixing tools. For all these reasons, therefore, it's not unreasonable when writing SCSS today to consider the potential that your code might need to be ported away from SCSS sometime in the future. That would indicate you should avoid using lots of SCSS-specific features when they're not really necessary, such as the nesting in your case.
If you want readability, add comments, which you should be doing anyway.
#article { ... }
/* The `#article_inner` element is inside `#article`.
#article_inner { ... }
More generally, I would question an ID-based approach to writing CSS. Presumably you intend to specify a bunch of properties on #article-inner, like font size, background, padding, or whatever. I've seen CSS where there are a dozen properties or more. What is the point? You might as well just write the properties in a style attribute directly on the element; at least then, you'd only have one file (the HTML) to manage. Instead, knowledgeable CSS designers create small, utility-like classes that can be applied to many elements. For instance, they might define a PaddedGrayBox class, that handles the padding and background. Then, they write in their HTML
<div id='article-inner' class='PaddedGrayBox FloatRight...'>
Now this is more readable. Someone looking at the HTML can immediately see what kinds of styling are being applied. If you take this approach consistently, you may find that you are able to do away with using IDs altogether, although I know that would be quite a departure for jQuery-oriented programmers who believe that doing $('id') (or getElementById) on every other line is the core of JavaScript programming.
I am just getting started with less. In an attempt to mmake less ugly Bootstrap's multitude of classes on tags, I have attempted to write some simple wrappers in less.
The entireity of my code is below.
// Import boostrap.
#import "./less/bootstrap.less";
// General classes for content.
focus {
.span12;
}
content {
.span8;
}
side {
.span4;
}
The purpose of this less file is to provide nice looking wrappers that do a single thing, such as Bootstrap's .span12 class. I will, in time, extend this to buttons of sorts.
Either way, I am running into a problem when compiling the less file using lessc style.less.
The error it gives is:
NameError: .span12 is undefined in /srv/http/www/style.less on line 6, column 5:
5 focus {
6 .span12;
7 }
I have found some documentation with the .makeColumn(i) class but the problem with that is Bootstrap already has perfectly good media queries and I wanted to avoid writing my own.
Is there anyway to wrap the classes that already have the media queries or do I need to just suck it up and write my own for my wrappers?
You are going to run into a few major problems in this approach.
First, there are issues in that Bootstrap is dynamically generating the .spanX series of classes, so they are not immediately accessible as mixins, as I note in this answer.
Second, some of Bootstrap's span code is not set by the .spanX series, but is done through an attribute selector of [class*="span"] (see, as of this writing, line 602 of the mixins.less file; they are also extensively used in the responsive files for the #media rules). This selector code would not be picked up by a .span12 inclusion of code, and if you are not putting .span12 in your code, then your code will not have those properties applied. So you need to work around that.
There may be other issues not immediately obvious, but the point is, if you want to use Bootstrap for grid purposes (especially responsive), it is probably best to use it as it is designed. If you do not, then it is best to go and copy the Bootstrap code and modify it as you desire to make your own reduced grid code (if your intent is to use less overall classes in your html).
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.
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.
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.