Less Web Development Cookbook - Bass Jobsen - E-Book

Less Web Development Cookbook E-Book

Bass Jobsen

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Aimed at those who want to overcome the limitations of CSS, through this book you will begin to harness the efficiency of Less by building advanced, responsive, and modern websites. Experienced web developers, students, and even web designers will find this guide very useful as they enhance their CSS skills.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 460

Veröffentlichungsjahr: 2015

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Less Web Development Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Getting to Grips with the Basics of Less
Introduction
Downloading, installing, and integrating less.js
Getting ready
How to do it…
How it works…
There's more…
See also
Installing the lessc compiler with npm
Getting ready
How to do it…
How it works…
There's more…
See also
Using less.js with Rhino
Getting ready
How to do it…
How it works…
There's more…
Declaring variables with Less for commonly used values
Getting ready
How to do it…
How it works…
There's more…
See also
Setting the properties of CSS styles with mixins
Getting ready
How to do it…
How it works…
There's more…
Writing more intuitive code and making inheritance clear with nested rules
Getting ready
How to do it…
How it works…
There's more…
See also
Creating complex relationships between properties
Getting ready
How to do it…
How it works…
There's more…
See also
Using the built-in functions of Less
Getting ready
How to do it…
How it works…
There's more…
See also
Using namespaces to make your code reusable and portable
Getting ready
How to do it…
How it works…
2. Debugging and Documenting Your Less Code
Introduction
Debugging your code with less.js
Getting ready
How to do it…
How it works…
There's more…
See also
Using CSS source maps to debug your code
Getting ready
How to do it…
How it works…
There's more…
See also
Using Chrome Developer Tools to debug your code
Getting ready
How to do it…
How it works…
There's more…
See also
Commenting your code in Less
Getting ready
How to do it…
How it works…
There's more…
See also
Building style guides with tdcss.js
Getting ready
How to do it…
How it works…
See also
Building style guides with StyleDocco
Getting ready
How to do it…
How it works…
There's more…
See also
3. Using Variables and Mixins
Introduction
Deriving a set of variables from a single base variable
Getting ready
How to do it…
How it works…
See also
Value escaping with the ~"value" syntax
Getting ready
How to do it…
How it works…
There's more…
See also
Using variable interpolation
Getting ready
How to do it…
How it works…
There's more…
See also
Redeclaring variables based on lazy loading
Getting ready
How to do it…
How it works…
There's more…
See also
Using mixins to set properties
Getting ready
How to do it…
How it works…
There's more…
See also
Declaring a class and mixin at once
Getting ready
How to do it…
How it works…
There's more…
See also
Using selectors inside mixins
Getting ready
How to do it…
How it works…
There's more…
See also
Using parametric mixins
Getting ready
How to do it…
How it works…
There's more…
See also
4. Leveraging the Less Built-in Functions
Introduction
Converting units with the convert() function
Getting ready
How to do it…
How it works…
There's more…
See also
Using the default() function
Getting ready
How to do it…
How it works…
There's more…
See also
Embedding images with data URIs
Getting ready
How to do it
How it works…
There's more…
See also
Formatting strings
Getting ready
How to do it…
How it works…
There's more…
Replacing a text within a string
Getting ready
How to do it…
How it works…
There's more…
See also
Working with lists
Getting ready
How to do it…
How it works…
There's more…
Using mathematical functions
Getting ready
How to do it…
How it works…
There's more…
See also
Using the color() function
Getting ready
How to do it…
How it works…
There's more…
See also
Evaluating the type of a value
Getting ready
How to do it…
How it works…
There's more…
Creating color objects with RGB values
Getting ready
How to do it…
How it works…
There's more…
See also
Getting information about a color
Getting ready
How to do it…
How it works…
See also
Creating a color variant with the darken() and lighten() functions
Getting ready
How to do it…
How it works…
There's more…
Creating overlays of two colors with Less
Getting ready
How to do it…
How it works…
There's more…
See also
5. Extending and Referencing
Introduction
Referencing parent selectors with the & operator
Getting ready
How to do it…
How it works…
There's more…
See also
Referencing to the parent selector more than once
Getting ready
How to do it…
How it works…
There's more…
See also
Changing the selecting order with the & operator
Getting ready
How to do it…
How it works…
There's more…
See also
Using extend to merge selectors
Getting ready
How to do it…
How it works…
There's more…
Using extend inside a ruleset
Getting ready
How to do it…
There's more…
See also
Extending with the all keyword
Getting ready
How to do it…
How it works…
There's more…
See also
Extending with media queries
Getting ready
How to do it…
How it works…
There's more…
See also
Using extend to reduce the compiled CSS size
Getting ready
How to do it…
How it works…
There's more…
See also
Using extend as an alternative for a mixin
Getting ready
How to do it…
How it works…
6. Advanced Less Coding
Introduction
Giving your rules importance with the !important statement
Getting ready
How to do it…
How it works…
There's more…
See also
Using mixins with multiple parameters
Getting ready
How to do it…
How it works…
There's more…
See also
Using duplicate mixin names
Getting ready
How to do it…
How it works…
There's more…
See also
Building a switch to leverage argument matching
Getting ready
How to do it…
How it works…
There's more…
See also
Avoiding individual parameters to leverage the @arguments variable
Getting ready
How to do it…
How it works…
There's more…
See also
Using the @rest... variable to use mixins with a variable number of arguments
Getting ready
How to do it…
How it works…
There's more…
Using mixins as functions
Getting ready
How to do it…
How it works…
There's more…
See also
Passing rulesets to mixins
Getting ready
How to do it…
How it works…
There's more…
See also
Using mixin guards (as an alternative for the if…else statements)
Getting ready
How to do it…
How it works…
There's more…
See also
Building loops leveraging mixin guards
Getting ready
How to do it…
How it works…
There's more…
See also
Applying guards to the CSS selectors
Getting ready
How to do it…
How it works…
There's more…
Creating color contrasts with Less
Getting ready
How to do it…
How it works…
There's more…
See also
Changing the background color dynamically
Getting ready
How to do it…
How it works…
There's more…
See also
Aggregating values under a single property
Getting ready
How to do it…
How it works…
There's more…
See also
7. Leveraging Libraries with Prebuilt Mixins
Introduction
Importing and downloading prebuilt mixin libraries
Getting ready
How to do it…
How it works…
There's more…
See also
Using namespacing with prebuilt libraries
Getting ready
How to do it…
How it works…
There's more…
See also
Creating background gradients
Getting ready
How to do it…
How it works…
There's more…
See also
Building unlimited gradients with Less Hat
Getting ready
How to do it…
How it works…
There's more…
See also
Building a layout with the CSS3 flexbox module
Getting ready
How to do it…
How it works…
There's more…
See also
Getting retina ready with Preboot
Getting ready
How to do it…
How it works…
There's more…
See also
Generating font-face declarations with Clearless
Getting ready
How to do it…
How it works…
There's more…
See also
Improving your website's SEO with 3L mixins
Getting ready
How to do it…
How it works…
There's more…
See also
Leveraging sprite images with Pre
Getting ready
How to do it…
How it works…
There's more…
See also
Creating bidirectional styling without code duplication
Getting ready
How to do it…
How it works
There's more…
See also
Creating animations with animations.css
Getting ready
How to do it…
How it works...
There's more…
See also
Creating animations with More.less
Getting ready
How to do it…
How it works…
There's more…
Building semantic grids with semantic.gs
Getting ready
How to do it...
How it works...
There's more
See also
Building an alternative for fluid grids with Frameless
Getting ready
How to do it…
How it works…
See also
Building a fluid responsive grid system
Getting ready
How to do it…
How it works…
There's more…
See also
8. Building a Layout with Less
Introduction
Using CSS Reset with Less
Getting ready
How to do it...
How it works...
There's more...
Using the box-sizing property with Less
See also
Importing and organizing your Less files
Getting ready
How to do it...
How it works...
There's more...
Importing files with the @import directive
Getting ready
How to do it...
How it works...
There's more...
See also
Building a grid with grid classes
Getting ready
How to do it...
How it works...
There's more...
See also
Creating responsive grids
Getting ready
How to do it...
How it works...
There's more...
See also
Building a semantic grid with mixins
Getting ready
How to do it...
How it works...
There's more...
See also
Applying the flexbox grid on your design
Getting ready
How to do it...
How it works...
There's more...
See also
Integrating a navigation menu in the layout
Getting ready
How to do it...
How it works...
There's more...
See also
Repositioning your content
Getting ready
How to do it...
How it works...
There's more...
See also
9. Using Bootstrap with Less
Introduction
Downloading and installing Bootstrap
Getting ready
How to do it...
How it works...
There's more...
See also
Customizing Bootstrap with variables
Getting ready
How to do it...
How it works...
There's more...
See also
Making custom buttons
Getting ready
How to do it...
How it works...
There's more...
See also
Making custom panels
Getting ready
How to do it...
How it works...
There's more...
See also
Making custom navigation bars
Getting ready
How to do it...
How it works...
There's more...
See also
Extending components using :extend
Getting ready
How to do it...
How it works...
There's more...
See also
Reusing Bootstrap's grid
Getting ready
How to do it...
How it works...
There's more...
See also
Using Bootstrap classes and mixins
Getting ready
How to do it...
How it works...
There's more...
Extending Bootstrap with your own mixins
Getting ready
How to do it...
How it works...
There's more...
See also
Making custom color schemes with 1pxdeep
Getting ready
How to do it...
How it works...
There's more...
See also
Autoprefixing Bootstrap's CSS
Getting ready
How to do it...
How it works...
There's more...
See also
10. Less and WordPress
Introduction
Installing WordPress
Getting Ready
How to do it…
How it works
There's more…
See also
Developing your WordPress theme with Less
Getting ready
How to do it…
How it works…
There's more…
See also
Integrating Bootstrap into your WordPress theme
Getting ready
How to do it…
How it works…
There's more…
See also
Using Semantic UI to theme your WordPress website
Getting Ready
How to do it…
How it works…
There's more…
See also
Customizing Roots.io with Less
Getting ready
How to do it…
How it works…
There's more…
See also
Building a WordPress website with the JBST theme
Getting ready
How to do it…
How it works…
There's more…
See also
11. Compiling Less Real Time for Development Using Grunt
Introduction
Installing Node and Grunt
Getting ready
How to do it...
How it works…
There's more...
Installing Grunt plugins
Getting ready
How to do it…
How it works...
There's more...
Utilizing the Gruntfile.js file
Getting ready
How to do it…
How it works...
Loading Grunt tasks
Getting ready
How to do it…
How it works...
Adding a configuration definition for a plugin
Getting ready
How to do it…
How it works...
See also
Adding the Less compiler task
Getting ready
How to do it…
How it works...
There's more...
Creating CSS source maps with the Less compiler task
Getting ready
How to do it…
How it works...
There's more...
Cleaning and minimizing your code
Getting ready
How to do it…
There's more...
Adding the watch task
Getting ready
How to do it…
How it works...
There's more...
Adding the connect and open task
Getting ready
How to do it…
How it works…
Adding the concurrent task
Getting ready
How to do it…
How it works…
Analyzing your code with CSS Lint
Getting ready
How to do it…
How it works...
There's more...
Removing unused CSS using Grunt
Getting ready
How to do it…
How it works...
See also
Compiling style guides with Grunt
Getting ready
How to do it…
Automatically prefix your code with Grunt
Getting ready
How to do it…
How it works…
There's more...
Installing the Grunt LiveReload plugin
Getting ready
How to do it…
How it works…
Index

Less Web Development Cookbook

Less Web Development Cookbook

Copyright © 2015 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing and its dealers and distributors, will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: January 2015

Production reference: 1250115

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78398-148-9

www.packtpub.com

Credits

Authors

Bass Jobsen

Amin Meyghani

Reviewers

Fahad Ibnay Heylaal

Dave Poon

Steve Workman

Commissioning Editor

Ashwin Nair

Acquisition Editors

Richard Brookes-Bland

Richard Harvey

Content Development Editor

Akashdeep Kundu

Technical Editors

Shashank Desai

Novina Kewalramani

Mrunmayee Patil

Rikita Poojari

Copy Editors

Gladson Monteiro

Sarang Chari

Project Coordinator

Milton Dsouza

Proofreaders

Lauren E. Harkins

Paul Hindle

Amy Johnson

Indexer

Monica Ajmera Mehta

Production Coordinator

Conidon Miranda

Cover Work

Conidon Miranda

Foreword

I became interested in Less after starting work on a project to expand a complex web application that had just two large CSS files (one went over IE's limit for a number of selectors in a file), and it used a regex replacement for theme variables—it was a nightmare. There was no link between colors that were clearly visually linked and numbers that were clearly related, and the connection was not obvious and copy/pasted blocks of CSS, scattered throughout the file. At first, it looked manageable, but then as we made changes and fixed bugs, we found that changing something at one place meant having to find several other places where change was required. What was worse, perhaps, was that developers were just adding yet another more complex selector to override another specific place—ad infinitum—until there were older, simpler selectors that weren't even used anywhere. I thought there must be a better way and found Less, which is a superset of CSS, focused on fixing these kind of maintainability problems by making CSS more declarative. I started off with my involvement by porting Less.js to dotless and then became an integral part of the team, taking over from Alexis in maintaining and expanding Less.js to keep up with the demands of the ever-evolving WWW, third-party library usage, and new ideas for CSS management.

I still consider that the primary job of Less is to allow the web developer to have maintainable CSS in their project. For this, abstraction of variables, splitting them up into separate files, and abstraction of common selectors and properties is the most important task (though a long way from what Less can do). We do not implement every feature request but instead try and choose those that have the biggest impact. We are generally against a feature that just provides a different way of doing something. Sometimes this means the solution to problems is not the most obvious one. I hope this will encourage developers to create code with consistent patterns, and I would urge them to try and keep their Less code simple and consistent and ensure it follows the same kind of generally accepted maintainability approaches that are applied to more traditional programming languages. Where common problems would be better served with new Less features, I hope we identify them and always welcome input, discussions, and help to our Github repository. However, it was a recent aim of the project to enable plugins for Less so that projects that need it can implement their own extensions without burdening the core project with support, for instance, functions for 10 different color models.

One plugin I would really like to push people to use is Less-plugin-autoprefixer. In the future, older browsers will not be in use and old polyfills (such as SVG Gradient backgrounds) and prefixed properties will be, if not a thing of the past, a less common occurrence. By using this plugin, you can write your CSS in a forward-thinking way and do not have to bloat it with mixins for polyfills that will be repeated across every project you will work on.

The features most asked for, which I've implemented over the last couple of years, have tended to focus on using libraries. I think this reflects the rise of people using CSS frameworks such as Bootstrap to get a head start at the beginning of a project in order to avoid reimplementing the bare bones. This I think is very positive as it promotes reuse and reduces the number of ways in which fundamentals are done. The biggest problem that remains with libraries is around picking out the bits you want to keep and customizing the library into a project's particular need. Hopefully, Less' import reference feature, not Sass-like extension will help us with this.

As with any language, problems always present themselves out of nowhere, and it always helps to get a head start on good solutions. So keep your solutions maintainable and elegant and enjoy reading this book.

Luke Page

Technical Lead Developer, Scott Logic Ltd. (http://uk.linkedin.com/pub/luke-page/35/81b/3b6)

About the Author

Bass Jobsen has been programming for the Web since 1995, covering everything from C to PHP, and is always on the hunt to find the most accessible interfaces. Based in Orthen, the Netherlands, he has also written Less Web Development Essentials, Packt Publishing, which is a fast-paced tutorial that covers the fundamentals of Less (Leaner CSS) when used in web development.

Bass uses Less in his daily job for web design tasks, WordPress theme development, and other Twitter Bootstrap apps.

He is always happy to help those with questions (http://stackoverflow.com/users/1596547/bass-jobsen), and he writes a blog you can find at http://bassjobsen.weblogs.fm/.

Also, check out his Bootstrap WordPress starters theme (JBST) and other projects at GitHub (https://github.com/bassjobsen).

This book is for Colinda, Kiki, Dries, Wolf, and Leny.

Writing this book wasn't possible without the support of my family, Caroliene, and the people of Vivent. Richard Harvey is a patient and excellent motivator and critical reader. Akashdeep Kundu helped me to dot the i's and cross the t's. I'd also like to thank the reviewers of this book, Dave Poon, Steve Workman, and Fahad Heylaal, for their critical and valuable suggestions that made this book even better.

Last but not least, I should not forget to thank the Less core Team: Alexis Sellier (@cloudhead), Jon Schlinkert (@jonschlinkert), Luke Page (@lukeapage), Marcus Bointon (@Synchro), Mária Jurčovičová (@sommeri), Matthew Dean (@matthew-dean), Max Mikhailov (@seven-phases-max), and all the other contributors who have made coding Less possible in the first place.

Amin Meyghani is a designer and developer currently working at HD MADE (http://hdmade.com/), making automation tools, websites, and apps. He is also a lead developer at Flitti (http://flitti.com/), leading the team to make next-generation gamification apps. In addition to arts and technology, Amin has always been passionate about teaching. He takes advantage of every opportunity to share his knowledge with the world through books, blogs, or videos. You can find his works and blogs at http://meyghani.com/. When Amin is not coding, he is either enjoying Persian food or mastering his Persian calligraphy techniques.

I would like to thank my family for always supporting me and filling my life with love and hope. I owe them this book, as they have always been there for me even in the most difficult times.

About the Reviewers

Fahad Ibnay Heylaal is a developer who hails from Bangladesh and is currently living and working in Amsterdam. Mostly known for being the creator of Croogo (a CMS based on the CakePHP framework), he has progressed to become more of a frontend developer over the last couple of years. If he isn't coding, chances are high that he will be seen cycling around the beautiful canals of Amsterdam.

Dave Poon is a UX/UI designer, web developer, and entrepreneur based in Sydney. He graduated from Central Queensland University with a degree in multimedia studies and a master's degree in IT. He began his career as a freelance graphics and web designer in 1998 and currently works with web development agencies and medium-sized enterprises. He began his love affair with Drupal afterward and worked for a variety of companies using Drupal. Now, he is evangelizing good user experience and interaction design practices to start-ups and enterprises.

Currently, he is a design lead at Suncorp, one of the biggest financial institutions in Australia. He is the cofounder of Erlango (http://erlango.com), a digital product development and design startup located in Sydney and Hong Kong that creates user-centered digital products for clients and users. He is also the cofounder of SpikeNode (http://spikenode.com) which is, a platform for DevOps automation.

He is the author of Drupal 7 Fields/CCK Beginner's Guide, Packt Publishing.

Also, he is the technical reviewer of the books Drupal Intranets with Open Atrium, Advanced Express Web Application Development, and Mastering Web Application Development with Express, all by Packt Publishing.

I would like to thank my wife, Rita, for her endless patience and support. Without her, whatever I do would be meaningless.

I would also like to thank my father for his continued encouragement.

Steve Workman is a frontend web engineer and an organizer of the London Web Standards group. He is a champion at creating high-performance sites with the latest web technologies and making developers' lives easier with tools and new languages.

I'd like to thank the whole Less community for creating this great language and my wife, Emily, for always being there.

www.PacktPub.com

Support files, eBooks, discount offers, and more

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com, and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Free access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.

Preface

CSS has dramatically changed since its very first emergence, and it is continuing to evolve. In particular, the emergence of CSS3 has added many new features to CSS, including gradients and animations. Along with this are many new opportunities to build websites using only CSS and HTML. Developers are no longer dependent on techniques such as Flash and other tricks to build interactive and fancy websites.

CSS3 has played an integral role in building responsive websites, where CSS media queries have made it possible to apply some styles dependent on the width of the browser's viewport only.

Despite this improvement, CSS is inherently, at its core, a simple style sheet language that lacks some fundamental programming features such as variables, functions, and operators. The need for more maintainable CSS, especially with the explosion of complex web apps, has made CSS preprocessors such as Less a necessity in enabling us to write more readable and manageable versions without breaking cross-browser compatibilities.

Although Less cannot magically change CSS, it certainly provides us with the tools to help structure, modularize, debug, and maintain small or large CSS projects more easily. By extending CSS with variables, functions, and mixins; nesting CSS selectors; and allowing you to follow the don't repeat yourself (DRY) principle of software programming, Less behaves more like a programming language in a way that CSS never was. Despite some of the programming characteristics of Less, you should not be put off by this; by being built as a superset of CSS, its features are implemented in the CSS way and it follows W3C standards where possible. Designers and developers who are familiar with CSS will find coding in Less very natural. Because Less fixes these shortcomings of CSS, the best time to start using Less is now!

In this book, you are going to explore the Less preprocessor, most of its core, and some of its less frequently used features. Through these very easy-to-follow and practical recipes, you will learn how to write more maintainable and scalable CSS. You will explore making components and structures through reusable mixins and extends. We will also learn about frameworks that are based on Less, exploring their features and how they can be seamlessly integrated into your own projects. In addition, you will learn how to use prebuilt mixin libraries for your current or upcoming projects. Finally, you will look at debugging techniques that have been available for other preprocessors and are now available to Less through source maps. By the end of this book, you will have an extended knowledge and a good understanding of the power of Less, its libraries, and the important features it has to offer to make writing your CSS more natural, productive, and intuitive.

What this book covers

Chapter 1, Getting to Grips with the Basics of Less, shows you how to install the Less compiler for client- and server-side usage. After the installation, you will be shown how to make use of the basic features of Less: using variables, mixins, operations, built-in functions, and namespaces; how to nest your rules will also be on the menu here!

Chapter 2, Debugging and Documenting Your Less Code, shows you how to debug your Less code using your CSS source maps and browser developer tools. You will also be introduced to style guides and learn how to properly comment your code.

Chapter 3, Using Variables and Mixins, covers the advanced usage of variables and mixins in Less. After reading this chapter, you will know how to use variables to create reusable Less code and use mixins to make your CSS properties interactive.

Chapter 4, Leveraging the Less Built-in Functions, explains the different types of built-in functions of Less. You will find examples of each type of function, including functions for color manipulation and mathematical operations.

Chapter 5, Extending and Referencing, shows you how to extend and reference selectors and properties to help you write better CSS and reduce the size of the compiled CSS code. You will learn to change the order of selectors and merge them.

Chapter 6, Advanced Less Coding, walks you through the process of parameterized mixins and shows you how to use guards. A guard can be used with as if-else statements and make it possible to construct interactive loops in Less.

Chapter 7, Leveraging Libraries with Prebuilt Mixins, explains how to install and use the libraries of prebuilt mixins. You will explore different libraries such as Less Elements, Less hats, and Preboot to build background gradients, grids, and animations in Less, among others.

Chapter 8, Building a Layout with Less, takes you through the process of creating a complete website layout with Less. The layout will be built with a responsive and semantic grid and will include a vertical menu. Finally, you will also learn how to use iconic fonts with Less.

Chapter 9, Using Bootstrap with Less, shows you how to customize Bootstrap and its components using Bootstrap's Less source files. You will also learn how to use Bootstrap's mixins to make semantic and reusable layouts and components.

Chapter 10, Less and WordPress, shows you how to use Less when theming your WordPress site. This includes examples of the Roots.io, SemanticUI, and JBST WordPress themes. You will be shown how to customize the WooCommerce plugins with Less along with integrating Less into your other WordPress themes and plugins.

Chapter 11, Compiling Less Real Time for Development Using Grunt, shows you how to set up a Less compiler using Grunt for real-time compilation. It will also show you how to use several Node modules for your Less development. By the end of this chapter, you will be very comfortable setting up a development environment with Grunt and its plugins.

What you need for this book

The latest version of Less.js can be downloaded for free from http://www.lesscss.org/. You will definitely need a text editor to write your code; however, it does not matter which text editor or operating system you use. You will also need a modern web browser, namely the latest versions of Mozilla Firefox, Google Chrome, or Microsoft Internet Explorer. Please note that some recipes, especially in the final chapter, require some basic familiarity with the command line. All the tools used in the last chapter are cross-platform and are available for free, so you should be fine using your favorite operating system. Grunt plugins can be found by visiting http://gruntjs.com/plugins.

Who this book is for

This book is mainly intended for web developers and designers who are comfortable with CSS and HTML. If you are someone with some experience with CSS, you will find the learning curve of understanding the Less syntax to be less steep. Although this book is beneficial to those who have had some experience with using Less, web developers and designers who would like to use this book as a gateway to learning the program can still benefit and harness its true power.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).

To give clear instructions on how to complete a recipe, we use these sections as follows:

Getting ready

This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from: https://www.packtpub.com/sites/default/files/downloads/B01849_Coloredimages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the ErrataSubmissionForm link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. Getting to Grips with the Basics of Less

In this chapter, we will cover the following topics:

Downloading, installing, and integrating less.jsInstalling the lessc compiler with npmUsing less.js with RhinoDeclaring variables with Less for commonly used valuesSetting the properties of CSS styles with mixinsWriting more intuitive code and making inheritance clear with nested rulesCreating complex relationships between propertiesUsing the built-in functions of LessUsing namespaces to make your code reusable and portable

Introduction

Leaner CSS (Less) is a preprocessor for CSS code. This chapter will guide you through the installation of Less. It can be used on the command line via npm (or Rhino) or downloaded as a script file for a web browser. Other third-party compilers are available too.

Although client-side compiling is not suitable for production, it is very useful to develop and test your code. A client-side compiler will run in any modern browser and show you the effect of your coding in real time. On the other hand, the server-side-compiled CSS code can be minified and used for production. Note that client-side compiling doesn't save the output and compiles your code again after each browser reload, while the output of the server-side compiler will be saved in a static CSS file.

You will also see that Less, in contrast to CSS, is a programming language for writing CSS more efficiently. It adds built-in functions, variables, and mixins with a lot more to offer to CSS, which helps you to meet the Don't repeat yourself (DRY) principle of software programming and reuse your code. Variables enable you to define the commonly used values only once, and mixins create the reusable blocks of code. You will work more effectively and find that you will spend less time on debugging and maintaining your projects.

Less extends the CSS language, which also means that valid CSS code is valid Less code. Whoever is familiar with CSS will find that the process of learning Less has a flat learning curve and is very intuitive.

After installing Less, the other recipes in this chapter will show you its basic features and how to use them to write a better, reusable, and more maintainable CSS code.

Installing the lessc compiler with npm

For server-side compilation, Less comes with a command-line compiler for Node.js. The node package manager (npm) can be used to install the Less command-line compiler.

Note

Node is a platform built on Chrome's JavaScript runtime called V8, allowing you to easily create fast and scalable network applications.

Getting ready

If you have not installed Node.js and npm on your system yet, you will have to do this first. You can do this by following these steps:

Download the Node.js source code or a prebuilt installer for your platform from http://nodejs.org/download/.Install Node.js, which includes npm, on your system.

In the Installing Node and Grunt recipe in Chapter 11, Compiling Less Real Time for Development Using Grunt, you can read about installing Node.js and npm on your system in more detail. After installing npm, you can simply run the following command:

npm install --global less

How to do it…

For this recipe, you will first need to create a simple Less file and save this file, which for instance might be example.less. You can try the following code in your example file:
@color: red; .paint() { color: @color; } p { .paint(); }
After creating the Less file in the preceding format, you will need to save your file (which may be example.less or whatever filename you have chosen). If you have chosen example.less, you can run the following command in your command prompt:
lessc example.less
After running the lessc command, you will see it output the following CSS code in the console:
p { color: #ff0000; }

How it works…

If you are new to Less, the example Less code used inside example.less may contain some syntax that is completely alien to you. The code defines a @color variable and a paint() mixin. The Declaring variables with Less for commonly used values recipe explains the basics of variables in Less, while the Setting the properties of CSS styles with mixins recipe does the same for mixins.

By default, the lessc compiler outputs to stdout. You can redirect the output to a CSS file with the following command:

lessc example.less > example.css

Running the lessc compiler without any parameters will give you a list of options for the compiler.

You can use the -x option to compress your output as follows:

lessc -x example.less > example.css

In a similar manner, you can use either the --clean-css option for a more involved minification, or the --source-map option to create a v3 CSS source map. In the Using CSS source maps to debug your code recipe in Chapter 2, Debugging and Documenting your Less Code, you can read more about CSS source maps and Less. Note that in version 2 of Less, the --clean-css option has been moved into a plugin. The usage is similar: just install the plugin (npm install -g less-plugin-clean-css), then make use of the --clean-css argument.

There's more…

There are many other third-party compilers for Less with a compressive list available at http://lesscss.org/usage.

With grunt-contrib-less, you can compile your code with Grunt. For Gulp, you can use gulp-less. The Compiling style guides with Grunt recipe in Chapter 11, Compiling Less Real Time for Development Using Grunt, shows you how to build a development workflow with the Grunt task runner.

In this recipe, you read about Grunt and Gulp, which are JavaScript task runners or build systems. Comparing with Grunt's build system, Gulp's build system is relatively new. Gulp uses streams and code over configuration, which makes it more simple and intuitive.

See also

In Chapter 11, Compiling Less Real Time for Development Using Grunt, you can read all you want to know about GruntTo read more about Gulp, you can visit http://gulpjs.com/The Gulp Less plugin can be found at https://github.com/plus3network/gulp-less

Using less.js with Rhino

Less also runs inside Rhino, which is an open source implementation of JavaScript written entirely in Java. It is typically embedded into Java applications to provide scripting to end users. Rhino enables you to use the original less.js distribution in a pure JVM environment.

Getting ready

To use less.js inside Rhino, you will have to download and install Rhino from the following links:

Download and install the latest version of Rhino from https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino/Download_RhinoDownload the Rhino version of less-rhino-x.x.x.js and lessc-rhino-x.x.x.js from https://github.com/less/less.js/tree/master/dist

How to do it…

Open your text editor and create a file named example.less. The example.less file can contain, for instance, the following code:
@base-color: red; h1 { color: @base-color; }
Now you can run the following command in your command prompt:
java -jar js.jar -f less-rhino-1.7.0.js lessc-rhino-1.7.0.js example.less
The preceding command should output the following lines of CSS code:
h1 { color: #ff0000; }

How it works…

Rhino enables Java to run the JavaScript code, while js.jar runs the Less compiler and generates the CSS output.

To write the output of a file, you will have to append the filename of the CSS files to the list of commands, as follows:

java -jar js.jar -f less-rhino-1.7.0.js lessc-rhino-1.7.0.js example.less example.css

You can also add options for the compiler. You can add the -x option to compress the output as follows:

java -jar js.jar -f less-rhino-1.7.0.js lessc-rhino-1.7.0.js -x example.less

The preceding command will then output the following line of CSS code:

h1{color:#f00}

There's more…

A Less compiler for Java has been built with Rhino. You can find out more information about this Less compiler for Java along with how to download it at https://github.com/marceloverdijk/lesscss-java.

Declaring variables with Less for commonly used values

Less allows you to use variables. You can assign a variable a value, which will be called a declaration. After a variable is declared, you can use the variable anywhere in your code to reference its value. Variables allow you to specify widely used values in a single place and then reuse them throughout your code. Defining once also means you have to edit it once when you want to change its value.

Getting ready

Open your text editor and create a file named example.less. Variables will start with @ and will have a name with examples, including @color, @size, and @tree. To write the name, you are allowed to use any alphanumeric characters, underscores, and dashes. Using this as an elaborate example, @this-is-variable-name-with-35-chars is a valid variable name.

How to do it…

Start with creating a simple HTML5 file named index.html, as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Use variables in Less</title> <link rel="stylesheet/less" type="text/css" href="example.less"> <script src="less.js" type="text/javascript"></script> </head> <body> <h1>Color your page with variables</h1> <p>Hello Less</p> <button>Click here</button> </body> </html>
You then need to create the example.less file, which should contain the following code:
@base-color: red; h1 { color: @base-color; } p{ color: @base-color; } button { color: @base-color; }
After the first two steps, you will end up with the following folder and file structure:After creating the files as described in the preceding steps, you can open index.html in your browser.Now, change the first line of code @base-color: red; to @base-color: green; and reload your browser.

How it works…

As you can now see, changing the font color of the h1, p, and button text is easy as you change @base-color only once. The only thing you need to do is change the single line of the code: @base-color: red;. In the Downloading, installing, and integrating less.js recipe, you can read how to use the watch function of less.js to reload your browser automatically after changing and saving the example.less file.

Variables in Less are defined as the equivalent to statics in other programming languages. You assign a value to a variable once and use it everywhere in your code. To think of it in another way, this is like defining the value of the gravitational constant (for the force of gravity) or pi in your code. Both these values become constants once they are declared and so do not change at runtime. In fact, you can still change or redeclare them in Less, as explained in the There's more… section of this recipe.

You can assign any valid Less (or CSS) property value to a variable. Valid property values include the numbers, strings, lists, CSV lists, and escaped values. Strings and numbers can be used together to define values with units. For instance, the following code will show you a declaration for a length in pixels:

@length: 100px;

Other examples of valid variable declarations can be found in the following code:

@color: red; @list: a b c d; @csv-list: a, b, c, d; @escaped-value: ~""dark@{color}";

There's more…

Less uses the last declaration wins and lazy loading rules, which play an important role and make redeclaration of a variable suitable for customization.

See also

You can read more about the usages of redeclaration variables for customization in the Redeclaring variables based on lazy loading recipe in Chapter 3, Using Variables and Mixins

Setting the properties of CSS styles with mixins

In Less, mixins hold a set of properties that can be reused for different rulesets. The properties of a mixin are included in the ruleset. The mixin itself does not generate output to the final CSS. They look like normal classes (or an ID ruleset, starting with #). Although they are optional, most mixin declarations end with parentheses, which prevent the mixins from compiling into the source. A mixin with parentheses is called a parametric mixin. You can read more about parametric mixins in the Using parametric mixins recipe in Chapter 3, Using Variables and Mixins.

Getting ready

Open your text editor and create a file named mixins.less. In this file, define a mixin for rounded corners, as follows:

.rounded-corners() { border-radius: 5px; }

You will also need an index.html file containing some HTML elements to which you can give rounded corners.

How to do it…

You first need to create a valid HTML5 document named index.html with the following elements:
<header>the header</header> <p>this is a paragraph</p> <footer>the footer</footer>

Make sure the head section of your index.html file also contains the following code:

<link rel="stylesheet/less" type="text/css" href="project.less"> <script src="less.js" type="text/javascript"></script>

Note that the preceding code references a Less file called project.less instead of mixins.less

After creating the index.html file, you can start writing your Less code, which will give the HTML elements rounded corners. Since mixins can be reused, it will be a good practice to write them in a separated file, enabling you to import the mixins in your other projects too.Now, create your project.less file. This file imports the mixin(s) from the mixins.less file using the following code:
@import "mixins.less";
After creating the files, visit the mixins.less file. Here, write the following code:
.rounded-corners() { border-radius: 5px; }
Following this edit, you can give an HTML element rounded corners by adding the rounded-corners() mixin call to its property list. Finally, your project.less file will look as shown in the following code: