Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

CSS Best Practices

329 views

Published on

A brief overview of the current state of CSS Best Practices.

The talk will cover Frameworks, Methodologies, Naming Schemes and Preprocessors.

I’ll also go over how this fits into the changes we’ve been making to the CSS structure on the JUST EAT International Platform.

Published in: Internet
  • Be the first to comment

  • Be the first to like this

CSS Best Practices

  1. 1. Ashley Nolan Senior Web UI Engineer : CSS Best Practices So, for those of you who don’t know me, or simply can’t remember my name, I’m Ash, and as the screen suggests, I’m going to be talking a bit about CSS best practices today. Explain what we’ve been working on as part of Platform improvements for ConsumerWeb.
  2. 2. @AshNolan_ : Ok, so first of all, I want to take you all back – way back to 2004. So that’s 11 years ago, and that was about when I first started out building professional websites for people other than just building geocities websites for myself. Now back in 2004, things were pretty different. It was the year that Facebook was founded, IE6 held the biggest market share of any browser on the web, and the BBC Sport Website looked like this…
  3. 3. @AshNolan_ :http://ashn.uk/bbc2004 So things were pretty different and I’m sure you can tell just by looking at this that CSS was pretty different back then too. Thankfully we’ve moved on from these times and CSS has evolved tremendously in this time.
  4. 4. @AshNolan_ : 11 years on, CSS is still a language that is hugely important on the web today, and is still one of my favourite languages to develop with. Although this is apparently what the logo for CSS looked like originally – and I think it’s ironic that the logo for a language that represents style on the web, has absolutely no style itself… CSS is a really expressive language. At it’s core it’s deceptively simple, but the more experience you gain using it, the more nuances and intricacies you find.
  5. 5. @AshNolan_ : Now unfortunately, when starting out with CSS, it can feel a little bit like this. To be honest, no matter how long you work with CSS, you’ll inevitably get this feeling every now and again. I’ll usually get it when debugging code in older Android browsers, but this is how I used to feel writing CSS that worked with IE6 as well. But if you’ve been developing websites for some time, you’ll know just how far CSS has come in a relatively short space of time with the introduction of CSS3…
  6. 6. @AshNolan_ : Now before CSS3 came along, times were tough in the trenches of front-end development. Developers were being forced to make rounded corners out of images and fonts with things like SIFR or Cufon – these were terrible terrible times. I still have the scars and therapy bills to prove it. We’re finally now getting to a place with developments like Flexbox and Webfonts where we can almost do everything we want to in CSS. But the problem is we’re still not quite there yet – we’re still waiting for new specs to be fleshed out and the browsers to implement all of the features that could help us. Also, CSS3 doesn’t help us with the structure and the maintainability of our code. So how do we mitigate for this in the meantime?
  7. 7. @AshNolan_ : - Frameworks - CSS Methodologies - Naming Schemes - CSS Preprocessors CSS Best Practices What am I going to talk about? Well that’s what I’m going to talk about today! So I’m going to go through some of the ways in which writing CSS has changed. So that’ll involve going over frameworks, CSS Methodologies, CSS Naming Schemes, and CSS Preprocessors, but there’s only so much I can fit into one presentation. So it’d be great if there’s any topics that people would like me to go into more detail in the future, or have any questions about anything that I cover today to let me know – so please do just grab me afterwards or send me a hipchat and I’ll do my best to help where I can.
  8. 8. @AshNolan_ : - Structure - Maintainability - Flexiblility The other thing that I’m going to keep coming back to are these 3 points. So I would say that these are the three main aspects of writing good CSS on any project of any size – it should have good structure, it should be maintainable and it should be as flexible as possible. Hopefully, as I go through the varying techniques and tools you can use when writing CSS, you’ll see how each one can help contribute to achieving these 3 points.
  9. 9. @AshNolan_ : Frameworks So, let’s start by looking at frameworks and how they can be applied to what we do at Just Eat. So CSS frameworks have been popular for some time now…
  10. 10. @AshNolan_ : There are quite a lot of front-end frameworks around now – here are a few of the more popular ones. Bootstrap, Foundation, InuitCSS and Pure.css – some deal with just CSS, others try and give you a framework for all of your front-end processes.
  11. 11. @AshNolan_ : Bootstrap Bootstrap is probably the most well known front-end framework. It’s a tool that is really great for prototyping or getting projects up and running quite quickly because it gives you a lot of features straight out of the box.
  12. 12. @AshNolan_ : The problem with larger frameworks like Bootstrap and Foundation, is that they tend to give you way more than you actually need… …and so your project ends up a little bit like this cat – pretty bloated and not as flexible as it ought to be.
  13. 13. @AshNolan_ : So as an example, we have been using Bootstrap in the International ConsumerWeb codebase and it’s in use on all of the pages apart from the new SERP page. This is a screengrab I took of some the Bootstrap files in ConsumerWeb – and so we automatically have all of this CSS before anyone else starts adding in their own styles for other aspects of the site.
  14. 14. @AshNolan_ : CSS Best Practices Mo' Frameworks, Mo' Problems? 1. Bit of a black hole – it’s difficult to tell what’s being used out of each framework 2. Hard to remove later 3. Can lead to CSS Bloat So this is a bit of a black hole – it’s very difficult to tell how much or how little of Bootstrap a project is actually using. When you actually look into the CSS for ConsumerWeb, it turns out we aren’t actually using that much of it at all …A result of this kind of black-hole effect, it can be hard to remove parts of a framework from a project at a later date if you wanted to. This ties you in to the framework, and creates an unnecessary dependency on your project. It can also lead to the produced CSS being far larger in size than is needed, because it will include a whole load of utility classes that the site isn’t using.
  15. 15. @AshNolan_ : Some frameworks attempt to give you everything, when you should be aiming to keep your front-end code lean Some frameworks attempt to give you everything, when you should be aiming to keep your front-end code lean. So it’s important to be suitably cautious when adding any framework to a project. They often give you way more than you actually need, and you should always weigh up the benefits against the potential downsides before including it, as it’s a lot harder to remove later on than it is to add to a project.
  16. 16. @AshNolan_ : But frameworks aren’t evil – there are a lot of use cases for them and they can be very useful for developers. For us, and for our projects at Just Eat, the most important thing is to learn from how frameworks are currently doing things, and why they’re doing those things…
  17. 17. @AshNolan_ : because then we can take the best parts and build our own conventions, because on a larger platform it’s really important to do that. So what parts of a framework are useful to look at and learn from?
  18. 18. @AshNolan_ : Structure Well it’s the structure and conventions that a framework helps to encourage that is the most useful aspect of a framework. We can do this ourselves by ensuring that our team uses the same conventions and ensuring that ConsumerWeb has a clearly defined structure – this is all stuff that the changes to the ConsumerWeb CSS that we’ll be rolling out shortly is aimed at addressing. So we’re trying to get away from relying on big frameworks and instead will be aiming to just add the things we need, as we need them.
  19. 19. @AshNolan_ : - Structure - Maintainability - Flexiblility - Structure - Maintainability - Flexiblility So we can improve the structure of our CSS by putting good conventions in place and learning from how frameworks are doing things currently…but we want to ensure we not only have well structured CSS, but that it’s also easily maintainable and flexible. So to have a project that displays all of these traits, it relies on having a well documented process, as well as for the people who are writing the CSS to understand current best practices and standards.
  20. 20. @AshNolan_ : CSS Methodologies So this is where CSS Methodologies and naming schemes come in. So a CSS Methodology is just a way of thinking about writing and structuring your CSS. They’ve become more talked about recently and there are quite a few of them about, but essentially they all share very common ground.
  21. 21. @AshNolan_ : - Modular Code - Thinking (and styling) in components - Avoid undoing styling, encourage extension of styles - Reuse - Consistency CSS Methodologies What they encourage So CSS Methodologies are all about encouraging: – very modular code – Thinking and Styling in components – To avoid undoing styles, and instead extend styles with each class that you add to an element – they encourage writing CSS that can be reused across components – and encouraging consistency in the styles that you write – which is really important on a project like ours where you have many people editing the same CSS.
  22. 22. @AshNolan_ :https://smacss.com/ As far as I’m concerned, if I could advise anyone writing CSS to go and read one book on methodologies, it would be this one: SMACSS by Jonathan Snook. I actually read this about halfway through working on the BBC Good Food Redesign a few years ago, and it pretty much described and addressed the majority of the issues I came across while writing the CSS on that project. So SMACSS is all about making your CSS more modular, so it’s easily reusable, but the book also goes into a lot of detail over idea’s around components and common issues people face on larger projects – and the author applies this to the work that he did while he worked at Yahoo.
  23. 23. @AshNolan_ : - SMACSS - OOCSS - Atomic Design - ITCSS - BEM - SUIT CSS Methodologies Loving the Acronyms Now in terms of other methodologies out there, here are a few more of the most popular ones. – So you’ve got SMACSS, which I just mentioned… – OOCSS – Extending classes to build up styles on components… – Atomic Design – Breaking components down into the smallest reusable chunks and building larger modules out of these… – ITCSS – about having clearly defined structure and modularity in your code Now the important thing to consider when thinking about all of these is to understand that they don’t all have to work in isolation. In fact, their true power comes from combining them for your own needs. For example, I tend to use parts of all of these when I write CSS.
  24. 24. @AshNolan_ : It’s best to understand and adapt CSS methodologies and naming schemes, as that’s where their true power lies. So it’s good to remember that, as with any kind of best practice advice, it’s best to understand and adapt CSS methodologies and naming schemes, as that’s where their true power lies. It’s by doing this that you can adapt the knowledge specifically for your project and for your team. One of the most obvious examples of this is when using CSS Naming Schemes…
  25. 25. @AshNolan_ : Naming Schemes i.e. BEM or SUIT So naming schemes are a great example of where it is best to understand and adapt a concept of writing CSS to best suit your needs. Naming schemes have become very popular over the last couple of years. They are heavily related to CSS methodologies as they fit well into component driven CSS and that’s why a lot of people have started using them. So the idea of having a naming scheme is so that everyones CSS has a consistent feel to it, and when you’re writing CSS in a more modular way, breaking the parts of your webpage down into components, a naming scheme helps to describe the relationship between the classes in your CSS.
  26. 26. @AshNolan_ : Now naming schemes aren’t designed to be restrictive. By using them, we’re not trying to make people do something they don’t want to. They are simply to encourage people in the same team to write CSS classes in roughly the same kind of way, much like it’s sensible to enforce coding patterns when writing code for any programming language so that it looks consistent across a project.
  27. 27. @AshNolan_ : Naming Schemes Key Aspects of a naming scheme 1. Consistency between classnames 2. Show the relationship between classes 3. Easy to spot modified components and extensions 4. Provides consistent state/utility classes So there are several key aspects to using a naming scheme. 1. To keep consistency between classnames – so that they look similar throughout the project 2. Show the relationship between classes so that it’s clear from looking at a class which component it is a part of 3. They help to show when someone has extended a class and modified it, reusing the existing styles 4. And they help people write consistent state and utility classnames (such as active or open on an accordion)
  28. 28. @AshNolan_ : Naming Schemes Key Aspects of a naming scheme (BEM) – Blocks i.e. -> .nav – Elements i.e. -> .nav-item – Modifiers i.e. -> .nav--inline Naming schemes work by writing our classes in a certain way. So we split our components up into clear chunks. We have blocks, which is the base of our components. Elements, which are the pieces that make up our blocks. Elements therefore only make sense within the context of the block they belong to. If this isn’t true, then the class you give that element may be a component in it’s own right. Modifiers are used when we need to create a block (or component) that is very similar to an existing one, but with a slightly different appearance of behaviour.
  29. 29. @AshNolan_ : Blocks Example of blocks
  30. 30. @AshNolan_ : Elements Elements
  31. 31. @AshNolan_ : Modifiers Modifiers
  32. 32. @AshNolan_ : So in terms of the JUST EAT Search Page for example… We can think of it in terms of blocks like this
  33. 33. @AshNolan_ : Naming Schemes CSS Naming Scheme (based on BEM and SUIT) /* Descriptors use camelCase if more than one word: e.g. twoWords */ .skipToContent { ... } /* Child elements use single hyphens: - */ .list { ... } .list-item { ... } /* Modifier element use a double hyphen: -- */ .nav.nav--inline { ... } /* Element state: .is- or .has- */ .is-active { ... } http://ashn.uk/je-naming So to convey this relationship in our CSS, this is where the actual naming scheme comes in, and this is what we’ll be encouraging people to use in ConsumerWeb CSS going forward. This is very similar to something like BEM in it’s way of thinking, but the syntax is more similar to a naming scheme called SUIT (used by Twitter) – as it’s a little friendlier to look at and use. So you should be able to see the structure of the elements in a component by the classnames. So for example, if you have a list, it follows that .list-item is an element of that block, and you use a dash to indicate that in your class. Modifiers are defined by using double dashes. So if I have a .nav class, which is a vertical stacked navigation, and then later I want a component which is very similar to this, except that the elements are horizontally aligned rather than vertical, I can define that by using a modifier class such as .nav--inline. And element states always start with .is- or .has-. So rather than just writing a class of .active, we would use .is-active for example, so it’s easy to see which classes are related to state.
  34. 34. @AshNolan_ : Naming Schemes Before naming schemes… /* randomly chosen */ .searchResults { ... } .searchResults ul { ... } .searchResults .restaurants { ... } .searchResults .restaurants .firstRestaurant { ... } .searchResults .restaurants .rating { ... } /* States might look like this */ .active { ... } .valid { ... } http://ashn.uk/je-naming So by way of an example, this is what some CSS might typically look like when you aren’t using a naming scheme of any kind… So everything is very tightly coupled. You can’t reuse classes such as rating, as they’re specified quite deep. Also if you just looked at the HTML, you wouldn’t be able to link which classes were related to one another, and where one component ends and another begins. So what happens if we use a naming scheme instead?
  35. 35. @AshNolan_ : Naming Schemes After applying a naming scheme /* Clearly linked classes */ .searchResults { ... } .searchResults-listing { ... } .listing { ... } .listing-item { ... } .listing-item--first { ... } .listing-item-rating { ... } /* States */ .is-active { ... } .has-error { ... } http://ashn.uk/je-naming Here you can clearly see relationships between classes within a component. So you have classes specific to a searchresults components, then a more generic listing component. States are always defined with the same .is- or .has- prefixes, so they are easier to spot in your CSS and HTML as being a state.
  36. 36. @AshNolan_ : Naming schemes positively re-enforce modular and component driven CSS Using a naming scheme helps to re-enforce writing component driven CSS. Using components is a good idea because it encourages reuse of classes and actually using the C in CSS, which is the cascade – and when used properly, this is the most powerful thing about CSS. So I’ve talked a lot about making components in the last few minutes, but what do I actually mean by that in CSS?
  37. 37. @AshNolan_ : So, components in CSS are like LEGO. The aim is to be able to stick together a bunch of reusable classes so that you don’t have to reinvent the wheel every time you build a new page. Like in any other programming language, the smaller the piece of code, the more flexible it is likely to be later. So let’s look at a couple of examples of this specific to CSS.
  38. 38. @AshNolan_ : #restaurants { background-color: red; } #restaurants li { margin-bottom: 10px; } #restaurants li .logo { float: left; } CSS Methodologies – Thinking Modularly Doing it wrong So, this is an example of some CSS that you might see on a project. So what’s actually wrong with CSS like this?
  39. 39. @AshNolan_ : #restaurants { background-color: red; } #restaurants li { margin-bottom: 10px; } #restaurants li .logo { float: left; } CSS Methodologies – Thinking Modularly Doing it wrong ID’s are very specific Can’t reuse So using ID’s in general is a bad idea in CSS. They are highly specific selectors, as any styles you define using them are really hard to override later. They also don’t facilitate reuse of styles – you can’t use ID’s repeatedly on the same webpage, and so if you wanted a component similar to this on the same page, reusing these styles would be impossible. They also stop classes defined beneath them being reused, so in the code here, if I had a logo in a different part of my site and I wanted to use the same styling as this example, I’d have to define those styles again, because this .logo class only works when it’s inside an element with the restaurants ID on it.
  40. 40. @AshNolan_ : Using ID’s will bring you down, a bit like this dog. This was just a tenuous excuse to get this gif into the presentation because I like it so much.
  41. 41. @AshNolan_ : CSS Methodologies ID’s are a bad idea – demo http://codepen.io/ashleynolan/pen/BNGLpv?editors=110 So to show how this can be a problem, let’s take a look at a live example. http://codepen.io/ashleynolan/pen/BNGLpv?editors=110
  42. 42. @AshNolan_ : In short… …use ID’s for JavaScript hooks… …but not for CSS selectors Uniqueness is good in JavaScript, but less useful in CSS
  43. 43. @AshNolan_ : CSS Methodologies ID’s are a bad idea – demo http://csswizardry.com/2012/11/code-smells-in-css/ There was a great article on this written a couple of years ago, called 'Code Smells in CSS', by Harry Roberts. In it, he mentions a number of very useful points, but one of them is around IDs and why it’s a good idea to avoid them in styling – I’d definitely recommend taking a look at it if you get the chance.
  44. 44. @AshNolan_ : .restaurants { background-color: red; } .restaurants li { margin-bottom: 10px; } .restaurants li .logo { float: left; } CSS Methodologies – Thinking Modularly Doing it wrong Doesn’t make much sense outside of Search Results page So hopefully you’ve got the idea that using ID’s is a bad idea in CSS. But returning to our example from before, let’s consider that it was written with classes rather than using an ID. Now it still isn’t very modular – and that’s because using a classname such as restaurants is very specific to the item we are styling. If I did want to reuse these styles on another page because the look and feel was very similar, putting a class of .restaurants in code on that page doesn’t make much sense – it’s just confusing.
  45. 45. @AshNolan_ : .listing { ... } //generic component styles .listing--highlight { background-color: red; } .listing-item { margin-bottom: 10px; } .listing-item-img { float: left; } CSS Methodologies – Thinking Modularly Doing it well So a better way of doing it would be to refactor it so that you think of the feature rather than where in the site it actually sits. So in this case, a list of restaurants can instead be named as a listing. So you can create a listing class, which is the base of your component. This class should be as generic as possible so that it can be reused and extended later by other people. So if you know all of the listings on your site are going to have red backgrounds, include that in your base class. Otherwise, extend it with a modifier class, such as .listing--highlight here. Then instead of writing .listing li {}, we can instead use a class, as then it can be applied to any HTML tag later if needed. This makes the styles more reusable. It’s also clear that the styles are related to the .listing component, because of the naming scheme used. Similarly, instead of our .logo class, use something that links to our component if it’s related. Again this means we can reuse the styles later as well as giving a clear indication of hierarchy in your CSS.
  46. 46. @AshNolan_ : <a class="btn wide" href="">Button</a> .btn { width: 100px; background-color: red; } .wide { width: 200px; } CSS Methodologies – Thinking Modularly Extending classes – bad I also want to show you a couple of good example of extending classes and using naming schemes to show that. So in this example, if you’re just looking at your CSS file, you wouldn’t know that the .wide class was intended as an extension to the .btn class. So how can we make this better?
  47. 47. @AshNolan_ : <a class="btn btn--wide" href="">Button</a> .btn { width: 100px; background-color: red; } .btn--wide { width: 200px; } CSS Methodologies – Thinking Modularly Doing it well So instead we can write it like this. So this gives a really clear message that .btn--wide is an extension of the base .btn class.
  48. 48. @AshNolan_ : <div class="highlightDetails"> <p class="sponsored">Sponsored</p> </div> //can also be class="new" or class="offer" CSS Methodologies – Thinking Modularly Applying this to a real situation – current To give you an example of how this can work in a real situation on Just Eat, this was the HTML being used to show the labels on the search results page. So it would put, 'new' or 'offer' alongside the title. So how can we clean this up a bit?
  49. 49. @AshNolan_ : <div class="highlightDetails"> <p class="sponsored">Sponsored</p> </div> <p class="promo promo--sponsored">Sponsored</p> CSS Methodologies – Thinking Modularly Applying this to a real situation – improved We can make it a small component, where we have a base class of promo, and modifier classes that extend those styles. So this makes it really easy to reuse these styles later, but also makes it clearer in the HTML that the classes are related.
  50. 50. @AshNolan_ : Methodologies and naming schemes
 are good So hopefully, through the examples I’ve shown, you’ve got a sense of why it’s important to think about writing CSS in a more modular way and why naming schemes are a good idea. I’ve only really scratched the surface of it, but there’s lots of great books and articles out there that go into a lot more detail, and I’d highly recommend checking out a few of them if you get chance.
  51. 51. @AshNolan_ : Atomic OOBEMITSCSS http://ashn.uk/css-meths Sitepoint actually published a really good article on how methodologies can work together a couple of weeks ago – so go and read that, as well as SMACSS which I showed you earlier.
  52. 52. @AshNolan_ : CSS Preprocessors The final thing I want to cover is CSS preprocessors. As a front-end tool, Preprocessors are now pretty mature – lots of developers are using them, which is great because they are extremely useful. Preprocessors help to give us functionality that standard CSS doesn’t and I personally would find it hard to develop without one. Now preprocessors are nothing new in terms of our workflow at Just Eat – we use Less currently on ConsumerWeb, so I imagine most people are familiar with them – but I wanted to go over what I think their most useful features are as well, as some of the common mistakes that I’ve seen in the past.
  53. 53. @AshNolan_ : Why use them? So why use preprocessors at all? Well as I mentioned at the start of the talk – CSS has come a long way with CSS3, but we still aren’t quite there in terms of having all the functionality that we would like when authoring stylesheets. That’s where preprocessors come in. They help to give you features that aren’t currently possible with just vanilla CSS, some of which are being implemented in future versions of CSS. So what are a preprocessors most useful features? Well, for me, there are a few main features that make preprocessors an essential tool.
  54. 54. @AshNolan_ : Why use Preprocessors? I. File Organisation @imports 'reset'; // reset stylesheet @imports 'grid'; // grid styles @imports 'typography'; @imports 'components/navigation'; File organisation So being able to break up your CSS into manageable chunks and then concatenate them down into one CSS file when compiled. So here, you see we have our reset, grid and typography specific CSS and then we can start styling our components, such as our navigation, in different files as well.
  55. 55. @AshNolan_ : Why use Preprocessors? II. Variables $bp-narrow: 320; $bp-mid: 640; $bp-wide: 960; $img-path: '/assets/img'; // colours $color-primary: #333; $color-links: #0000FF; //blue http://ashn.uk/1M4mjgh Variables Variables are really handy especially for file paths, when using images for example, specifying your major breakpoints when using media queries, and for defining a clear colour–palette. Doing this also makes it easier to have a living styleguide based on your CSS, as you can use these base variables to show the main colours and font-sizes when stored in this way. http://ashn.uk/1M4mjgh
  56. 56. @AshNolan_ : Why use Preprocessors? III. Browser Prefixes (using autoprefixer) -webkit-transition: 250ms ease-out; -moz-transition: 250ms ease-out; -o-transition: 250ms ease-out; transition: 250ms ease-out; transition: 250ms ease-out; Browser Prefixes The other reason is the ease in which they can help keep your CSS more maintainable. In vanilla CSS, you need to specify and maintain the fallbacks for browser prefixes manually. This is ok, but it’s hard to manage over time and can lead to redundant code. With preprocessors you can tackle this in two ways – either using mixins (ok solution) or by using a plugin called AutoPrefixer (best solution). Using Autoprefixer, you can simply write the CSS properties as you would normally, specify the browsers that you would like to support, and the relevant prefixes get generated when your code is compiled.
  57. 57. @AshNolan_ : Why use Preprocessors? IV. Inlining Images (using postcss-assets) /* inline('path') automatically converts an image to a data uri */ background-image: inline('icon-arrow.png'); background-image: inline('logo-fb.svg'); Inlining images One of the biggest bottlenecks to performance on mobile is http requests, as they cost you a lot in terms of the amount of time spent looking up assets. Now, to avoid this, you can inline some of your images within your CSS, particularly icons that are an enhancement to text. So to do this, you can use a plugin that let’s you simply write inline() and this will convert the image specified into a data uri when your CSS gets compiled.
  58. 58. @AshNolan_ : PostCSS A new kind of processor? https://github.com/postcss Now Autoprefixer and postcss assets are actually plugins for a different kind of processor – and that’s a tool called PostCSS. PostCSS is actually a pretty new tool which has started to gain some attention because of the success of AutoPrefixer. So PostCSS is being labelled as different to preprocessors like Sass and LESS, but if you’ve never heard of it before, what’s the difference between a preprocessor and something like PostCSS?
  59. 59. @AshNolan_ : PostCSS - Lots of features, all rolled into one tool - Can’t extend if you need added functionality - Add features by adding plugins - Can write your own plugins
 if needed Standard Preprocessor (Sass / Less ) Preprocessors have lots of features, all rolled into one tool. But you’re stuck with those features unless you want to contribute to the tool itself, and even then it might not get accepted if you do that by whoever owns that project. PostCSS features are instead added by adding plugins. So imagine you start with a blank slate – you can then add just the functionality you require. So if you only want to be able to use variables, you can add a plugin that will do just that. The same goes for Nesting and browser prefixes (using autoprefixer), you simply add the relevant plugin and it’ll transform your code in the desired way This is great because you only include the functionality that you and your team need rather the the whole of a preprocessor.
  60. 60. @AshNolan_ : Essentially, you can create your own unique preprocessor out of PostCSS plugins Essentially, you can create your own unique preprocessor out of PostCSS plugins with as much or as little functionality as you require. Now if this all sounds too good to be true, at the present time it is a tiny bit. We actually looked into using PostCSS as an alternative to a traditional preprocessor in our workflow on ConsumerWeb, but currently it doesn’t quite have all of the features that we would want to be able to make that switch But…
  61. 61. @AshNolan_ : PostCSS can be used in addition to a preprocessor such as Sass to extend it’s functionality PostCSS can be used in addition to a preprocessor such as Sass to extend it’s feature set. So that’s exactly what we’ll be doing – we’ll use Postcss for features such as AutoPrefixer and image inlining, and as PostCSS grows, we may move more away from Sass, which is what we’ve gone with for our new workflow, and more towards using smaller modules with PostCSS.
  62. 62. @AshNolan_ : - Structure - Maintainability - Flexiblility Now, going back to the three points we mentioned right back at the start, I said that we’re always looking to achieve these 3 things when we write our CSS. Structure, Maintainability, Flexibility. Using a preprocessor definitely helps us to reach these goals when they are used responsibly.
  63. 63. @AshNolan_ : but… but…and there’s always a but…it’s that word 'responsibly' that is the most key in my last sentence…
  64. 64. @AshNolan_ : When we use tools like preprocessors we’ve got to make sure we don’t become like this dog. For me, preprocessors are brilliant things, but they can also be quite dangerous in the wrong hands.
  65. 65. @AshNolan_ : Irresponsible Preprocessing Nesting .availableTimesContainer { … .tablularDiv { … .dayOfTheWeekContainer { … .dayOfTheWeek { … .cell { … &.cell:hover, &.selected { … .modal { … &.modal.top { … .arrowUp { … } } } } For example, this was a legitimate piece of code I came across when I inherited a project from a freelancer at my previous company. Now my initial reaction when I see this type of code is something like…
  66. 66. @AshNolan_ :
  67. 67. @AshNolan_ : .availableTimesContainer .tablularDiv .dayOfTheWeekContainer .dayOfTheWeek .cell.cell:hover .modal.modal.top .arrowUp, .availableTimesContainer .tablularDiv .dayOfTheWeekContainer .dayOfTheWeek .cell.selected .modal.modal.top .arrowUp { … } .availableTimesContainer { … .tablularDiv { … .dayOfTheWeekContainer { … .dayOfTheWeek { … .cell { … &.cell:hover, &.selected { … .modal { … &.modal.top { … .arrowUp { … } } } } Irresponsible Preprocessing Nesting Now this kind of thing makes me almost as sad as when I was having to use stuff like SIFR, but the difference is that this is completely self inflicted. This actually compiles out to this (click) which is something we should never write in CSS. As developers, we have to be more responsible than this, but although this is an extreme example accentuated when using preprocessors, if I see deep nesting of any sort it’s a clear sign to me that someone doesn’t understand how to write modular CSS, with or without preprocessors.
  68. 68. @AshNolan_ : Keep selectors short and clear so that they are more extensible and reusable Try to keep your selectors short, so that they are more extensible and reusable. As a general rule, you should never be nesting more than 3 levels deep.
  69. 69. @AshNolan_ : .btn { font-weight: bold; } .header .btn { color: red; } .myOtherBtn { @extend .btn; } Irresponsible Preprocessing @extends //compiles to the following CSS .btn, .myOtherBtn { font-weight: bold; } .header .btn, .header .myOtherBtn { color: red; }
  70. 70. @AshNolan_ : .btn, %btn { font-weight: bold; } .header .btn { color: red; } .myOtherBtn { @extend %btn; } Irresponsible Preprocessing @extends using placeholders //compiles to the following CSS .btn, .myOtherBtn { font-weight: bold; } .header .btn { color: red; } Now this kind of thing makes me almost as sad as when I was having to use stuff like SIFR, but the difference is that this is completely self inflicted. This actually compiles out to this (click) which is something we should never write in CSS. As developers, we have to be more responsible than this, but although this is an extreme example accentuated when using preprocessors, if I see deep nesting of any sort it’s a clear sign to me that someone doesn’t understand how to write modular CSS, with or without preprocessors.
  71. 71. @AshNolan_ : Use preprocessors responsibly. Only use them when they help with structure and maintenance Be sensible with preprocessors – only use them when they help with your projects structure and maintenance. That’s the good thing about preprocessors, if you don’t know Sass or Less, you can simply write CSS and it’ll still work. So enhance where you can improve that base functionality. We have chosen to go with Sass on ConsumerWeb, as it is a bit more powerful than Less in terms of the features it offers, so if you’ve got any further questions about Sass and best practices around using it, just fire any questions my way.
  72. 72. @AshNolan_ : - Learn conventions from frameworks - Break your styles into components (naming schemes) - Preprocessors are good… - …but don’t forget CSS fundamentals - Aim for consistency and ease of setup CSS Best Practices In Summary So that’s it really. In summary…
  73. 73. Ashley Nolan Senior Web UI Engineer at : @AshNolan_ Thanks

×