Writing Maintainable, Modular and Scalable CSS

10 min read Original article ↗

Transcript

  1. Who Am I • Wrote my first HTML page 18

    years ago using Netscape Composer. • Converted a lot of designs, PSDs, Origamis to HTML/CSS/JS. • Worked with different sized companies and organizations as a front- end developer, a trainer and a consultant. • Currently work as head of software development and front-end developer at robusta. • When I am not fixing bugs or building web applications; I spend time trying to be a good parent.

  2. Introduction

  3. Maintainable Scalable Modular

  4. CSS Concepts Cascade Specificity Source Inheritance

  5. Creating *Layout* in Android Studio

  6. Creating *Layout* in Xcode

  7. • CSS is extremely simple to learn and to get

    started with. • One of the goals author had in mind while making CSS was backward compatibility. That meant when a parser encounter a rule it do not understand; it would simply skip that declaration and move on to the next. Unlike other languages which will throw exceptions and exit the program. • The problem with CSS is that it becomes hard to work with at any reasonable scale because picking class name is surprisingly extremely difficult.

  8. What makes CSS difficult • Everything is global. Selectors are

    matched against everything in the DOM. We need naming strategies to combat against this and keep things efficient (which are hard to enforce and easy to break). • It’s highly dependent on Source order. What an inexperienced developer can write at the end of the document can override and break rules written before it. • CSS grows over time. Smart people on great teams cede to the fact that they are afraid of their own CSS. You can't just delete things as it's so hard to know if it's absolutely safe to do that. So, they don't, they only add.

  9. Previous trials and patterns

  10. CSS Resets • CSS resets was an attempt from the

    authors to get browsers out of the equation. We began to see this popular pattern emerging. • It began in 2004 when Tantek Celik wrote a blog about a CSS snippet he's been using called undohtml.css (http://tantek.com/log/2004/09. html#d06t2354) It was a pretty light reset by today's standards.

  11. CSS Resets – cont. • Two years later 2 other

    resets emerged, the global YUI reset and Eric Meyer's reset. • Eric continued working on his reset year after year till 2009 then he decided to stop. • In 2011 Nicolas Gallagher and Jonathan Neal started working on Normalize.css It wasn't trying to remove the browser style instead it was trying to make all browsers have the same underlying defaults. It made it lighter and made it put far less coding on the frameworks and as a result it is nearly included on almost every open source project today.

  12. Structuring and Naming in CSS

  13. • In 2002 Tantek Celik wrote a blog post called

    A Touch of Class (http://tantek.com/log/2002/12.html#L20021216). His article recommended a few practices to write what he called "Good CSS". He suggested a few things like ₋ using semantic HTML. ₋ using context before classes. ₋ using structural class names over presentational class names like sidebar instead of right-bar and error instead of redtext. ₋ lowercase class names.

  14. A Touch of Class - examples

  15. A Touch of Class - examples

  16. Using structural class over presentational class

  17. Using structural class names over presentational class names

  18. Using structural class names over presentational class names

  19. BEM

  20. • BEM was presented back in 2007 in a Russian

    CSS conference. A naming convention that means (Block, Element & Modifier). It looks bizarre and ugly at the beginning but it's the basis for building a great, solid and scalable CSS. • BEM consists of: - Block is the root class like a tweet - Elements are the elements inside a block ... The pieces that construct that block. Like (tweet author, tweet text, tweet buttons) ... It consists of the block class name in addition to __ - Modifier can be added to a block or element and is meant to provide alternative states for the element (like promoted tweets) and they consist of the block/element name in addition to --

  21. BEM - example

  22. BEM - example

  23. Even easier BEM-ing with Sass 3.3

  24. Problems solved by BEM • Address the most complex and

    difficult problem with CSS; naming. • Gives you context for what this selector is used for. BEM unambiguously defines which CSS belongs to a piece of interface and so using it gives answers to questions "Can I remove this piece of code?”. • Provide self documented code. • Promote modularity and reusability. • Provide common terminologies between developers. • Eliminate subtree matches

  25. Common FAQ – cont. • Is this good to name

    modifiers corresponding to what they have in CSS? .block__element--border-bottom-5px Naming the modifiers corresponding to their CSS representation is not recommended. Indeed it looks not very nice but there are also practical reasons against it. Lately then the view of your components is changed, you will need to fix not only CSS but also the selectors.

  26. Common FAQ – cont. • What would be a class

    name for an element inside another element? .block__el1__el2? According to BEM method, block structure should be flattened; you do not need to reflect nested DOM structure of the block. So, the class names for this case would be: .block {} .block__elem1 {} .block__elem2 {} .block__elem3 {}

  27. Why BEM is awesome? BEM help us overcoming the cascading

    problem. BEM challenges the cascade by forcing the authors (us) to be incredibly mindful when it comes to naming limiting the wrong number of CSS classes through block namespaces and establishing relationships between blocks and elements rather than writing generic complex names.

  28. OOCSS

  29. OOCSS • In 2009 Nicole Sullivan presented what she was

    calling OOCSS. Nichole was saying that CSS authors where trying to protect themselves from the cascade by sandboxing their styles using ID driven modules. Nicole encouraged people to start writing low level reusable components. • Nichole explained on her post how she saved hundreds of lines of code by the module component. (http://www.stubbornella.org/content/2010/06/25/ the-media-object-saves-hundreds-of-lines-of-code/)

  30. OOCSS

  31. SMACSS and SUITCSS

  32. SMACSS In 2011 Jonathan Snook wrote a post called Thinking

    about CSS architecture introduced a project he was working on called SMACSS (Scalable and Modular Architecture for CSS) SMACSS is all about categorization: 1. Base -> Basic style for the elements (like links, paragraphs, headers) 2. Layout -> For the components that divide the page into sections and they have the (l-) prefix 3. Module -> Components on the webpage and they have no prefixes 4. State -> (is-) prefixed classes like (is-open, is-active) when a module is in a particular state. 5. Theme -> for other different styles that cannot really fit within the previous categories.

  33. Inverted Triangle CSS ITCSS is defined by Harry Roberts as

    a group of thoughts for writing a sane, scalable and managed architecture. It is compatible with CSS methodologies like BEM, SMACSS or OOCSS. The key principles of ITCSS is that it separates your CSS codebase to several sections (called layers), which take form of the inverted triangle

  34. • Settings – used with preprocessors and contain font, colors

    definitions, etc. • Tools – globally used mixins and functions. It’s important not to output any CSS in the first 2 layers. • Generic – reset and/or normalize styles, box-sizing definition, etc. This is the first layer which generates actual CSS. • Elements – styling for bare HTML elements (like H1, A, etc.). These come with default styling from the browser so we can redefine them here. • Objects – class-based selectors which define undecorated design patterns, for example media object known from OOCSS • Components – specific UI components. This is where majority of our work takes place and our UI components are often composed of Objects and Components • Trumps – utilities and helper classes with ability to override anything which goes before in the triangle, eg. hide helper class

  35. The specificity graphs

  36. With ITCSS • You can remove or add layers as

    you need them. No preprocessors? Remove the first two layers Want to add a testing layer? Add it before the Trumps • No longer have to worry about the end of the file. • Things never get more complicated, only bigger. • The specificity graph keep going upward.

  37. كع

  38. ATOMIC CSS

  39. People even suggested moving CSS to JavaScript

  40. Coding best practices

  41. What you should also do … • Understand the basic

    CSS feature will prevent you from writing redundant unnecessary code like: 1. applying display block or width 100% to a block element. 2. setting an element position to absolute value or floating it automatically shift its display to become a block. You don’t need to declare that it is a block again. 3. inline elements are not affected by width and height values. You shouldn’t apply width or height to an inline element. 4. vertical margins have no effect except on absolutely positioned elements and items inside a flex container.

  42. • Don’t use libraries that add a lot of styling

    to your stylesheet. Examples: 1. jQuery UI 2. Libraries that lack the flexibility to define your mark up for the elements (e.g. sliders, tabs … etc). 3. Libraries with poorly written CSS. You should check its stylesheet and be picky. • When using a framework, make sure that you are not including something it already include (like a reset). • Use only the parts of the frameworks that you need. Don’t include additional 100KB file just because you need a tooltip. • Use SVG or icon fonts for icons. They are super simple to style.

  43. Use CSS Writing Style Guide

  44. Use a Shame file

  45. On “the site must look the same across all browsers”

  46. Example: Sticky Footer

  47. Example: Equal height columns

  48. Example: Sticky content

  49. Perfectly separated content

  50. The “Pixel Perfect” Dilemma

  51. The process of converting a design into HTML and CSS

    is not complicated. Most of the elements the designers create can be easily converted to HTML and CSS. The complexity lies in doing it with maintainable and reusable code with few “magic numbers”. Design isn’t anything but a reference. It’s a document that provide guidelines. We lose a lot by treating it as a contract.

  52. Just because you can, does not mean you should

  53. Countless hours are wasted on every company on arguments and

    fights between graphic designers and user interface developers. They both hate each other instead of working together. Your job as a user interface or front-end developer is to help the graphic designer understand why adding this particular component with shadows is bad for maintainability and the graphic designer job is to listen to you and help you find a less complicated solution.

  54. Normalize and Abstract Develop a style guide to limit the

    colors and the dimensions of the elements you are using. “Can we make *this* button bigger”? It’s a common question we get everyday. It isn’t technically difficult. But it would require me to add one class just to satisfy this request. Why? Is it really worth it?

  55. https://dribbble.com/shots/1121606-Admin-Dashboard

  56. https://dribbble.com/shots/615232-Dropdown-Menu

  57. https://dribbble.com/shots/524735-Header

  58. Thank you! ahmadalfy [email protected]