39,59 €
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:
Seitenzahl: 460
Veröffentlichungsjahr: 2015
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
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
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)
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.
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.
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.
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.
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.
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.
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.
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.
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:
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.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
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.
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.
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.
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.
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 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.
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.
In this chapter, we will cover the following topics:
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.
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.
Node is a platform built on Chrome's JavaScript runtime called V8, allowing you to easily create fast and scalable network applications.
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:
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:
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:
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:
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 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.
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.
To use less.js inside Rhino, you will have to download and install Rhino from the following links:
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:
You can also add options for the compiler. You can add the -x option to compress the output as follows:
The preceding command will then output the following line of CSS code:
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.
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.
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.
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:
Other examples of valid variable declarations can be found in the following code:
Less uses the last declaration wins and lazy loading rules, which play an important role and make redeclaration of a variable suitable for customization.
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.
Open your text editor and create a file named mixins.less. In this file, define a mixin for rounded corners, as follows:
You will also need an index.html file containing some HTML elements to which you can give rounded corners.
Make sure the head section of your index.html file also contains the following code:
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: