Learning BEM for CSS - css

I'm looking and learning and implementing BEM into my company front-end framework using SASS.
Does it take a while for you to learn and implement its methodology?
I can see its benefits as I'm building a large application.

I've recently started using BEM for a work project and it has been an excellent experience learning so far. I highly recommend using it starting on a new project and it is easy to pickup and it is a massive improvement on code quality and abiding by some standards on how to style a new component or module of your application.
Why use BEM (Block Element Modifier)?
BEM stands for Block, Element, and Modifier. BEM was
created as an approach to front-end development designed with the
flexibility and ease of modification in mind. The main idea of BEM
methodology is to speed development process up and ease the teamwork
of developers. It is an abstract way to think about your design
without relying on HTML structure. BEM captures purpose and meaning
through it’s CSS classname syntax.
Block
A block is a component on your page that may be reusable and will hold
elements inside of it. Examples of a block would be a header, menu or
an image. A block can contain elements and other blocks.
Element
An element is something that will only ever exist inside the block. It
depends on the block to exist. Examples of an element would be a
header sub-title, menu item or image captions. An element can contain
other elements and modifiers.
Modifier
A modifier defines the appearance and behavior of either a block or an
element. The modifier indicates a state difference from the default.
Examples would be themes, active/inactive states or aligning.
Example:
.block {}
.block__element {}
.block--modifier {}
.block__element--modifier {}
.nav {}
.nav__item {}
.nav--footer {}
.nav__item--active{}
BEM has helped in being able to easily breakdown a design and find "elements" and "modifiers" for a Block within a design. BEM can also be applied to any project size small or large. Avoiding nesting also makes it easier to make adjustments to modules without breaking other inner parts of functionality. Code quality is also improved as the developer would think twice before adding in a hack css selector just to get something right.
My team also uses SMACSS "Scalable and Modular Architecture for CSS" along with BEM to split out our SASS into a number of modules. This allows to easily find a components styling without having to search through a massive long stylesheet. It makes new developers life easier to find styling and reading code. Again it is scalable for all project sizes.
You can read more on combining BEM and SMACSS here - Combining BEM and SMACSS.
Once you make the change you will wonder how you used to build projects. It makes styling a project much more straight-forward and less stressful with clean and modular code.

Related

BEM Common Styles

What is the best way of defining general non-block-specific styles throughout the site?
For example:
html
<div class="intro">
<p class="intro__text">foo</p>
</div>
<div class="profile">
<p class="profile__text">bar</p>
</div>
sass/css
.intro__text {
}
.profile__text {
}
.text {
margin-bottom: 0.5em;
}
If I wanted the text to be styled the same, would I (given I am using a pre-processor) #extend .text into the .intro__text and .profile__text classes, or just have all paragraphs throughout the site have a class of text?
Both those solutions seem slightly incorrect to me.
If I have a very common style, it feels like I'm going to be duplicating a lot of styles throughout my rendered css (bumping up the filesize) but having a class of text repeated all throughout my markup seems unnecessarily verbose and untidy.
Is there a best practice for this situation?
I can't say that there is the best way to do it. It depends on the structure of your project and what style your prefer. Both approaches are used in mostly code.
If you like to manage styles through css files - write #extend. However in case you want an element without common style you have to create a modifier for the el. For example - .profile__text--reset.
If you want declare common styles, your class list with common classes may become too long. But it is more clear and specific. And you have a possibility to manage it via javascript.
One improvement for this code is that it is better to use helpers with modifiers. For example, instead of simple .text use .text--sm or .text--m-sm. Or if you want only margin - .m-sm. But it is up to you.
You have several options:
Preprocessor (Sass/LESS/etc) mixins + clean-css/postcss cleaner — this way is simple and powerful, but not flexible, since it's not useful for dynamic landing pages, SPA, etc.;
Element of outer block mix (BEM/runtime mixin): class="intro__text grid__text" — in that way you just splitting manually visual and positioning styles and use their classes together;
Other block mix: class="intro__text paragraph paragraph--valuable" — almost like the previous variant but without linking to the abstract grid block, the best and the most flexible way (IMHO).
NB: Also you can extend BEM mixes with modifiers even in runtime, it's VERY powerful tool.
NB2: If you don't need dynamic web pages, you can freely use sass mixins. Personally I don't use sass/less mixins, only global variables for colors, grid, gaps, etc used in my own classes.

Copying CSS classes

Lets say that youre using Twitter Boostrap and you have their generic boostrap.css and other boostrap associated css files, and you want your own classes to have identical attributes to some of the given boostrap classes. To my understanding, you would not want to directly modify the css bootstrap files, but you would want to extend them by creating a custom.css file.
So without touching the boostrap files. How would I replicate a boostrap class for my own class? Would the only way be to copy and paste from the boostrap.css file. Or is there a way to do
.myownclass {
-- some command to replicate class 'alert alert-error' without repeating the CSS that has already been written
}
You could use a css preprocessor. Other ways already cited by other users are fine but using a css preprocessor is the best way.
Bootstrap is built using LESS, so you can use LESS. Take a look at here: http://bootstrap.lesscss.ru/less.html.
Also SASS can be used. According to me SASS is better. You find a tutorial here: http://www.1stwebdesigner.com/css/build-website-using-twitter-bootstrap-sass-1/
What are CSS preprocessors?
A browser can only understand CSS, as the styling technique for any DOM element being rendered. CSS, as a language has its own feature set, which at times might not be enough to create a clean and reusable chunk of rules. Eg. Not being able to reuse a collection of rules in multiple selectors, unavailability of variables which may lead to ambiguous pieces of data across the stylesheet. To overcome most of these limitations, the concept of a preprocessor was born – offering an advanced way of writing CSS, which extends the basic functionalities. This advanced code is later compiled as normal CSS code using respective compilers (which depends on what preprocessor you are using), which the browser will understand.
Should you use preprocessors?
The decision of adopting preprocessors for your next project, in my opinion, should be made after much analysis and solely depending on your expertise level and most importantly the project requirement and workflow of the team as a whole. Here are some tips that might help you come to a decision:
Not for beginners: If you are a beginner and starting to explore the fantastic world of CSS, I would suggest you get your hands dirty with normal CSS before moving into a framework or preprocessor of any sorts. It’s really important to understand and be able to use the core concepts of any language that you work with, and that’s true for CSS as much as any other programming language.
Are you a team of front end developers? As a team of front end developers, adopting preprocessors will be a great move. But only if somebody on the team really knows how to handle huge CSS files and structure them accordingly. By making use of the powerful features offered by the language, it is important to first structure the whole CSS into reusable chunks and define a strategy for CSS organization. Eg. Are you going with multiple CSS files for typography, forms, layout etc. Are you going for theme-able UI, where you might need to use variables extensively, etc.
Are you willing to cross the barrier? Adopting preprocessors means you are going to be implementing more programming concepts into your CSS coding approach. There will be a lot of concepts that are native to any basic programming language, which you might want to learn and implement, by using a preprocessor. This means, you will definitely need to brush-up your programming skills and might forever change the way you see a CSS code. If you are willing to cross this barrier, and feel ready to embrace the change confidently, this is for you.
In CSS this is not possible. The only way to do it, is to chain the classes in your html tags.
<div class="alert alert-error myownclass"></div>
If you are using less you can do it like this:
.myownclass {
.alert
.alert-error;
}
This will copy the settings from one class to another. The result will be the same as if you copy the contents of the class directly.
If you are using Sass you can do it without copying the class contents. Just reference the classes as shown below. This will not copy the contents, instead it will reference your custom class at the right position in your css code.
.myownclass {
#extend .alert;
#extend .alert-error;
}
Ref: Sass #extend
You would have to use LESS to avoid copy/paste:
.myClass {
.bootstrapClass;
}
Or you could use any of the other CSS preprocessors TBS has been ported to (Sass has one, not sure on the others).
You could give the element two classes - the original Bootstrap class, and then one of your own making. Then you would target it like this:
HTML
<h1 class="original_class myownclass">Hello</h1>
CSS
.original_class.myownclass {
// css code
}
Here's a little jsfiddle illustrating the concept: http://jsfiddle.net/ApEpr/
This does not require the use of a CSS preprocessor - it's just regular old CSS.

CSS Best practices when starting a new project

I wanted to know what's the best approach to take on, when starting work on a CSS of a big project? Because I see on most big projects (like wordpress) that they bunch all the classes sharing same properties together, however, how can you know before hand that they'll be matched, or is that the post-programming micro-work?
Anyway, Just wanted to know the best practises for grouping classes, ids and such, and what's the industry standard approach on this manner.
CSS Frameworks
For big projects, you'll likely want extra functionality on top of 'regular' css, like nesting, inheritance and mixins. Either one of these should get the job done:
SASS
xCSS
LESS
OOCSS
Performance optimization
Also, you'll want to do automatic performance optimization (concatenation, minification, and compression of source files), so take a look at:
Minify
or whatever suits your development platform.
Naming
Many large sites use some kind of prefix on class names to separate style classes from script classes. E.g.:
<div class="navigation dynHomepageNav">(...)</div>
Where the dyn* class is used as a selector in scripts, while the navigation class is used for styling. The benefit is you can have coders refactoring scripts without touching the design, and designers changing the templates without worrying about breaking functionality.
However, with modern Javascript frameworks and HTML5 you can do better; use semantic naming for IDs and classes, apply style using those IDs and classes, and use data-* attributes for all script hooks instead. Example:
<section class="navigation" data-hook="homepageNav">(...)</div>
Which you will style using the class identifier:
.navigation {
border: 1px dotted #9c9;
padding: 12px;
}
And script using the data hook (using James Padolsey's data selector attribute for jQuery):
$('section:data(hook="homepageNav")').fadeIn();
It may not be as concise or look as familiar as the good old use-semantic-classes-for-everything method, but it will create a neat separation of style and behavioral properties, which you'll appreciate once you have 50.000 lines of HTML and you need to revamp the design.

Can the re-usability concept be applied to css?

I was just checking out this page, and came across the fact that CSS can be OO(Object oriented). So, is it possible to apply the re-usability concept of OOPs to css? If yes then how?
It's not exactly OOP but using Sass, in particular its mixins and variables, will help to reuse your CSS.
http://sass-lang.com/
I don't know about CSS being OO, after all it's not even Turing-complete.
As for Sass, it bring complexity to what should remain, imho, a simple static set of rules.
But you can definitely achieve reuse-ability with CSS. Avoid CSS rules related to an ID, as they're not reusable, avoid big CSS definitions with everything from margins to backgrounds to font syle, create short CSS rules that define simple behaviors, then combine these rules by applying multiple classes to your HTML elements like <span class="big emboss red">. Each of these rules has a simple and obvious meaning and can be reused.
A good thing to write well structured and reusable css is http://lesscss.org/
CSS is not really OO in the sense of OOP, but yes, you can reuse CSS. I've used the OOCSS methodology in situations where I'm working with larger development teams on longer ongoing projects. We try to establish a base CSS framework and then build upon that using the OOCSS.
Pros:
developers, with a bit of documentation, can reuse the CSS without having to constantly come back to a UI designer to create new classes for them
should be easier to maintain long term
typically leaner CSS files (as you avoid doing one-off classes more than typical)
Cons:
you tend to have more classes in your markup class attributes
it's not semantic
everyone managing the CSS has to be on board and understand the concepts related to it (else you end up mixing your OOCSS with a bunch of one-off classes and end up with a bigger mess)

Best Practices - CSS Theming

Quite often when I design a website for a customer, I design his website with one (or multiple) CSS files that makes up the entire presentation layer. The thing is, usually, the customer's needs change drastically in terms of "website theming". He may end up asking to change from a blue/green color-based theme to a red/orange based one according to his tastes. The thing is, my file contains all the information including:
the positioning of elements
the background images of containers
the font size, color
What are the best practices for "decoupling" a CSS file to make it "theme" aware, while maintaining all its information on positioning?
My list of possible practices are as follow:
Use a default CSS file containing generic information and positioning, use child CSS files that implement only the background images, font-sizes and colors
Name your first CSS file (say here the blue/green one will be named "sky"). Implement another theme based on sky, overriding any CSS attributes needed to change the theme and name it (red/orange would be "crimson" for example).
EDIT: according to the great answers provided below, I updated the list of other possible solutions adding up to my list:
Use SASS, (best authored with Compass #see Andrew Vit) specifically their "Mixins" feature. It takes CSS and introduces a very DRY programmatic approach. You can override existing classes with it. -treefrog
Use an OOCSS approach. -Andrew Vit
A technique called independent blocks (article in Russian) that mimics a sort of namespacing using class prefix to seperate specific blocks. -angryobject
Three based stylesheets. Separating typography, position, and the reset stylesheet provided by Eric Meyer. -David Thomas
Use already standardized approaches used by known organisations such as the Dojo library, jQuery UI, etc.
-S .Jones
Which would be better in which possible case? Are there any other easily maintainable and flexible ways?
Best answer to date: Using SASS to make very flexible stylesheets. Of course this implies the slight learning curve, but according to a few reviews, SASS seems to be the next approach for dynamic stylesheets (along with HAML).
You should look into SASS, specifically their "Mixins" feature. It takes CSS and introduces a very DRY programmatic approach. You can override existing classes with it, making it perfect for what I think you're trying to do.
Link
Consider the approach suggested by OOCSS. The general idea is to separate the style concerns of your classes into more granular units, so that you end up using more classes in your markup instead of hanging all of your styling on too few classes with overlapping concerns.
This can be combined with some of the other suggestions. (I highly recommend authoring SASS with Compass!)
In situations where a theme is required I, personally, tend to use three base-stylesheets:
A reset stylesheet (typically Eric Meyer's)
A stylesheet for positioning of elements (margins, paddings, floats, etc)
Typography and colours
There is an awful lot of repetition in this approach, though, so #treefrog's answer may well be a better approach. The one saving grace I can offer for my approach, which is why it works well for me, is that it's easy to know where to go to change the title font from Arial to Times New Roman (or whatever), and where to find the background-colours for the page. Typically these are stored in a Wordpress-like arrangement:
http://www.example.com/css/reset.css
http://www.example.com/css/themeName/typography.css
http://www.example.com/css/themeName/layout.css
I know about a techniques based on using so-called independent blocks. A block here is a part of the page that can be described by its own layout and its own styles. There are some principles of that techniques like using only class attribute, not id; each block has a prefix; no styles outside blocks or minimum global styles. But those are optional more or less. Suppose you have a block:
<div class="b-my-block">
<span>some more content</span>
</div>
And a style for that block:
.b-my-block{
width:100%;
height:300px;
}
.b-my-block span{
background:red;
}
'b' here is the prefix for the block. You can have different prefixes for you needs. You may want to use prefix 'g' for some global classes that can be applied to and modify any other elements.
Then, if you want to extend this block or change it somehow, you can create a modification of this block with a class 'b-my-block_blue' for example:
<div class="b-my-block b-my-block_blue">
<span>some more content</span>
</div>
and a piece of css:
.b-my-block_blue span{
background:blue;
}
This a very very rude example. And i'm not sure if i was explanatory enough. But i'm trying to use this technique in my current project and it feels pretty good so far. There is an article on this in russian. Maybe someone could translate it in english, if it has some interest for the people here.
Good Question. +1
I think for simpler layouts, where you can get away with theme changes based only on colors defined within CSS, then it makes sense to separate your CSS files into a core 'structural' file and several themed versions.
For more complicated themes, where images are imported as key parts of the layout or theme, it's better to completely nest your resources under a theme. You can see examples of this by exploring the directory structures of Javascript packages like Dojo that allow you switch between multiple themes. If you look through "Tundra" or "Soria" directory structures within the Dijit library, you'll see which 'best practices' they employed in dividing up their CSS files.

Resources