Less Web Development Essentials Sample Chapter
Less Web Development Essentials Sample Chapter
Bass Jobsen
Currently, he writes a blog (http://bassjobsen.weblogs.fm/), programs LBS for mobile devices (http://www.gizzing.nl), makes cool websites (such as http://www.streetart.nl/), and counsels Jamedo Websites (http://www.jamedowebsite.nl/) in setting up the technical environment and requirements for their business. You can also check out his Bootstrap WordPress Starters Theme (JBST) and other projects at GitHub at https://github.com/bassjobsen. "I choose a lazy person to do a hard job. Because a lazy person will find an easy way to do it." Bill Gates
Acknowledgments
This book is for Colinda, Kiki, Dries, Wolf, and Leny. Recently, I reviewed Getting Started with Zurb Foundation 4 by Andrew D. Patterson and Learning Zurb Foundation by Kevin Horek. After finishing this book, I will start writing Less Web Development Cookbook for Packt Publishing. Although I have written many blogs and technical project requirements in the past years, this is the first book I have written to be published. Writing this book wasn't possible without the support of my family, Caroliene, and the people of Vivent. Richard Harvey was a patient and excellent motivator and critical reader. Sruthi Kutty helped me dot the i's and cross the t's. Finally, I will thank the reviewers of this book, Simone Deponti, Austin Pickett, and Marcus Bointon, for their critical and valuable suggestions, which make this book even better.
The owl in the preceding screenshot has been built with HTML5 and CSS3 alone. The live version can wink and look by pressing the buttons. Responsive designs allow you to build one version of your website with only one code base which functions well and looks good on different devices such as mobile phones, tablets, and desktops. There won't be any technical reason to build different mobile and desktop versions, as shown in the following screenshot:
With all this new stuff, the work of the CSS (or web) developer becomes more complex. A web developer needs to know about complex CSS3, the difference between browsers and devices, animations, and other style effects. Writing correct and functional CSS code will be the first thing; keeping this code readable, maintainable, and working on all major browsers will be the second thing. CSS files grow and become untidy in the development and maintenance processes. CSS doesn't have the ability to modify the existing values or reuse common styles. Also, doing math or defining variables is not possible in CSS. This is where Less comes into the frame. Less (Leaner CSS) is a dynamic stylesheet language designed by Alexis Sellier. Started in 2010, it is now maintained and extended by the Less core team. Less helps you make your CSS code maintainable, reusable, and prevent code duplications. In this book, you will learn how to write, compile, and understand Less. We will help you do faster and more cost-effective web development. You will get practical tips to integrate Less in your current and new projects. After reading this book, you will write clear and readable CSS3 with Less. Instead of spending your time on debugging your complex CSS code for a specific device or browser, you can pay more attention to your real design tasks. Your clients will be happy with your advanced and stable designs. This will reduce the development and maintenance time and hence the cost of designing. Less extends CSS with functions and variables. In a semantic sense, valid CSS is also valid Less. The initial versions of Less were written in Ruby; now, Less is written in JavaScript.
Less is called a CSS precompiler. This means that the end product will be used for production. The end product in this case will be valid, compact, and readable CSS code. Besides, the precompiling Less code can also compile in real time. Less offers server-side and client-side options to do this. Real-time client-side compilation via LESS.js in a modern web browser makes testing easy. Server-side compilations offer opportunities to build applications with Less as well as create dynamic CSS. Also, others know the power of Less. Projects such as Twitter's Bootstrap and Roots, a WordPress starter theme, both rely on Less. These projects build clear and extendable frameworks with Less. You can't ignore this proof. Stop writing cumbersome CSS with bugs and browser defects and learn about Less by reading this book. Less is open source and licensed under the Apache license. At the time of writing this book, the latest version is 1.7. The source code of Less will be maintained on GitHub. Everybody will be allowed to contribute to it. You can use Less free of charge.
[ 10 ]
Chapter 1
As a Less/CSS designer, you will be making use of the calculated CSS specicity in most cases.
[ 11 ]
After this, the number of IDs in the selector will be the next indicator to calculate specicity. The #footer #leftcolumn {} selector has 2 IDs, the #footer {} selector has 1 ID, and so on.
Note that in this case, an ID is a unique selector starting with #; the selector [id=] for the same HTML element counts as an attribute. This means that div.#unique {} has 1 ID and div[id="unique"] {} has 0 IDs and 1 attribute.
If the number of IDs for two declarations is equal, the number of classes, pseudo classes, and attributes of the selector will be of importance. Classes start with a dot. For example, .row is a class. Pseudo classes, such as :hover and :after, start with a colon, and attributes, of course, are href, alt, id, and so on. The #footer a.alert:hover {} selector scores 2 (1 class and 1 pseudo class) and the #footer div.right a.alert:hover {} selector scores 3 (2 classes and 1 pseudo class). If this value is equal for both declarations, we can start counting the elements and pseudo elements. The latest variable will be dened with a double colon (::) . Pseudo elements allow authors to refer to otherwise inaccessible information, such as ::first-letter. The following example shows you how that works. The #footer div a{} selector scores 2 (2 elements) and the #footer div p a {} selector scores 3 (3 elements). You should now know what to do when your style isn't directly applied. In most cases, make your selector more specic to get your style applied. For instance, if #header p{} doesn't work, then you can try adding a #header #subheader p{} ID, a #header p.head{} class, and so on.
[ 12 ]
Chapter 1
When Cascade and !important rules do not give a conclusive answer, specicity calculation seems to be a hard and time-consuming job. Although Less won't help you here, tools such as Firebug (and other developer tools) can make the specicity visible. An example using Firebug is shown in the following screenshot, where the selector with the highest specicity is displayed at the top of the screen and the overruled styles are struck out:
[ 13 ]
These mixins will not be explained in great detail now, but the following example shows how Less reduces the code needed to create a ex container. Using CSS, you might use the following code:
div#wrapper { display: -webkit-flex; display: -moz-flex; display: -ms-flexbox; display: -ms-flex; display: flex; }
Downloading the example code You can download the example code les for all Packt books you have purchased from your account at http://www.packtpub.com/. If you purchased this book elsewhere, you can visit http://www.packtpub. com/support/ and register to have the les e-mailed directly to you.
However, if you use Less, the same effect can be produced by inserting the following line of code:
div#wrapper { .flex-display; }
You can use Google Chrome to test your Flexbox layouts. At the time of writing this book, Firefox and Internet Explorer IE11 also offered full or better support for Flexbox layouts. Flexboxes have been mentioned because they have the potential to play an important role in the future of web design. For now, they are beyond the scope of this book. This book will focus on creating responsive and exible layouts with Less using CSS media queries and grids.
Please visit https://developer.mozilla.org/en-US/ docs/Web/Guide/CSS/Flexible_boxes for additional information, examples, and browser compatibility.
Compiling Less
After delving into the theory of CSS, you can nally start using Less. As mentioned earlier, it has the same syntax as CSS. This means any CSS code is, in fact, a valid Less code too. With Less, you can produce CSS code that can be used to style your website. The process used to make CSS from Less is called compiling, where you can compile Less code via the server side or client side. The examples given in this book will make use of client-side compiling. Client side, in this context, means loading the code in a browser and compiling Less code into CSS code using resources from the local machine. Client-side compiling is used in this book because it is the easiest way to get started while being good enough for developing your Less skills.
[ 14 ]
Chapter 1
It is important to note that the results from client-side compiling serve only for demonstration purposes. For production and especially when considering the performance of an application, it is recommended that you use server-side precompiling. Less bundles a compiler based on Node.js, and many other GUI's are available to precompile your code. These GUI's will be discussed towards the end of this chapter.
As you can see, a Less le has been added to this document using the following code:
<link rel="stylesheet/less" type="text/css" href="less/styles.less" />
[ 15 ]
When rel="stylesheet/less" is used, the code will be the same as for a style sheet. After the Less le, you can call less.js using the following code:
<script src="less.js" type="text/javascript"></script>
In fact, that's all that you need to get started! To keep things clear, html5shiv (which you can access at http://code.google. com/p/html5shiv/) and Modernizr (which you can access at http://modernizr. com/) have been ignored for now. These scripts add support and detection of new CSS3 and HTML5 features for older browsers such as IE7 and IE8. It is expected that you will be using a modern browser such as Mozilla Firefox, Google Chrome, or any version of Internet Explorer beyond IE8. These will offer full support of HTML5, CSS3, and media queries, which you will need when reading this book and doing the exercises.
You already know you should only use less.js for development and testing in most cases; there can still be use cases which do justice to the client-side use of less.js in production. To support less.js for older browsers, you could try es5-shim (https://github.com/ es-shims/es5-shim/).
Now, open http://localhost/index.html in your browser. You will see the Less makes me Happy! header text in its default font and color. After this, you should open less/styles.less in your favorite text editor. The syntax of Less and CSS doesn't differ here, so you can enter the following code into this le:
h1{color:red;}
Following this, reload your browser. You should see the header text in red. From the preceding code, h1 is the selector that selects the HTML H1 attribute in your HTML. The color property has been set to red between the accolades. The properties will then be applied onto your selectors, just like CSS does.
It is not necessary to have a web server that is running. Navigating to index.html on your hard drive with your browser should be enough. Unfortunately, this won't work for all browsers, so use Mozilla Firefox in order to be sure. The examples in this book use http://localhost/map/, but this can be replaced with something similar to file:///map/ or c:\map\, depending on your situation.
[ 16 ]
Chapter 1
[ 17 ]
Debugging is also easy with less.js. To use debugging or allow less.js to display errors, you can add the following line of code to your index.html:
<link rel="stylesheet/less" type="text/css" href="less/styles.less" /> <script type="text/javascript">less = { env: 'development' };</ script> <script src="less.js" type="text/javascript"></script>
As you can see, the line with less = { env: 'development' }; is new here. This line contains less as a JavaScript variable used by less.js. In fact, this is a global Less object used to parse some settings to less.js. The only setting that will be used in this book is env: 'development'. For more settings, check out the following website: http://lesscss.org/#client-side-usage-browser-options.
env: 'development' also prevents Less from caching. Less doesn't cache les in the browser cache. Instead, les are cached in the browser's local storage. If env is set to production, this caching could yield unexpected results as the changed and saved les are not compiled.
To try this new setting, edit less/styles.less again and remove an accolade to create an invalid syntax of the h1{color:red form and then save the le. In your browser, you will see a page like the following screenshot:
Besides syntax errors, there will also be name errors that are displayed. In the case of a name error, an undeclared function or variable would have been used.
[ 18 ]
Chapter 1
It is possible to set other settings for debugging, either in the global Less object or by appending the setting to the URL. For example, you can specify the dumpLineNumbers setting by adding the following lines of code to your HTML le:
<script type="text/javascript">less = { env: 'development',dumpLineNumbers: "mediaQuery" };</script>
Alternatively, you can add !dumpLineNumbers:mediaQuery to the URL. This setting enables other tools to nd the line number of the error in the Less source le. Setting this option to mediaQuery makes error reporting available for the FireBug or Chrome development tools. Similarly, setting this to comments achieves the same for tools such as FireLess. For instance, using FireLess allows Firebug to display the original Less lename and the line number of CSS styles generated by Less . FireBug, Chrome development tools, or the default browser inspect the element functions (which you can access by right-clicking on your browser screen) can also be used to see and evaluate the compiled CSS. The CSS is displayed as inline CSS wrapped inside a <style type="text/css" id="less:book-less-styles"> tag. In the example given in the following screenshot, you will see an ID with value less:book-less-styles. The value of this ID have been automatically generated by Less based on the path and name of the book/less/styles.less Less le:
[ 19 ]
[ 20 ]
Chapter 1
Vendor-specic rules
CSS3 introduced vendor-specic rules, which offer you the possibility of writing some additional CSS applicable for only one browser. At rst sight, this seems the exact opposite of what you want. What you want is a set of standards and practicalities that work the same with every browser and a standard set of HTML and CSS which has the same effect and interpretation for every browser. These vendor-specic rules are intended to help us reach this utopia. Vendor-specic rules also provide us with early implementations of standard properties and alternative syntax. Last but not least, these rules allow browsers to implement proprietary CSS properties that would otherwise have no working standard (and may never actually become the standard). For these reasons, vendor-specic rules play an important role in many new features of CSS3. For example, animation properties, border-radius, and box-shadow all depend on vendor-specic rules. Vendors use the following prexes: WebKit: -webkit Firefox: -moz Opera: -o Internet Explorer: -ms
[ 21 ]
For rounded corners with different radii, use a list with values separated by spaces: 10 px 5px 20px 15px;. The radii are given in the following order: top-left, top-right, bottom-right, and bottom-left. By keeping these rules in mind, you will see how Less can keep your code clean. You can open roundedcorners.html from the download section of this chapter in your browser, and open less/roundedcorners.less in your text editor. In your browser, you will see a representation of a header, body, and footer with rounded corners. The CSS for the header in less/roundedcorners.less looks like the following code:
#header{ background-color: red; -webkit-border-radius: 10px; -moz-border-radius: 10px; border-radius: 10px; }
You can see that using vendor-specic rules, the corners have been created with a radius of 10 pixels. If you were using CSS, you would have to repeat the vendor-specic rules three times for the header, footer, and body. In order to change these rules or add a vendor, you would also have to change the same code three times. To begin with, you will perhaps think, "Why not group the selectors?", in a fashion similar to the following code:
#header, #content, #footer{ -webkit-border-radius: 10px; -moz-border-radius: 10; border-radius: 10px; }
The preceding code is syntactically correct in order to write CSS or Less code, but as your code base grows, it won't be easy to maintain. Grouping selectors based on properties makes no sense when reading and maintaining your code. Such constructs will also introduce many duplicated and unstructured usages of the same selectors. With Less, you are able to solve these problems efciently. By creating a so-called mixin, you can solve the issues mentioned earlier. For the border radius, you can use the following code:
.roundedcornersmixin() { -webkit-border-radius: 10px; -moz-border-radius: 10px; border-radius: 10px; } [ 22 ]
Chapter 1
To use this mixin, you will call it as a property for the selector using the following code:
#header{ background-color: red; .roundedcornersmixin(); }
Looking at the original code in the less/roundedcorners.less le, you can see that the preceding code wouldn't be able to work for #content. The border radius for the content is 20 pixels instead of 10 pixels, as used for the header and footer. Again, Less helps us solve this efciently. Mixins can be called with parameters in the same way in which functions can be called in functional programming. This means that in combination with a value and a reference for this value, mixins can be called in order to set the properties. In this example, this will change to the following code:
.roundedcornersmixin(@radius: 10px){ -webkit-border-radius: @radius; -moz-border-radius: @radius; border-radius: @radius; }
In the .roundedcornersmixin(@radius: 10px) mixin, @radius is our parameter, and its default value will be 10px. From this point onwards, mixins can be used in your code. The .roundedcornersmixin(50px); statement will set the corners with a radius of 50px and the .roundedcornersmixin(); statement will do the same with a radius of 10px (default). Using this, you can rewrite less/roundedcorners.less so that it changes to the following code:
/* mixins */ .roundedcornersmixin(@radius: 10px){ -webkit-border-radius: @radius; -moz-border-radius: @radius; border-radius: @radius; [ 23 ]
Improving Web Development with Less } #header{ background-color: red; .roundedcornersmixin(); } #content{ background-color: white; min-height: 300px; .roundedcornersmixin(20px); } #footer{ background-color: navy; .roundedcornersmixin(); }
The less/roundedcornersmixins.less le from the downloads section contains a copy of this code. To use this, you also have to change the reference in your HTML le to <link rel="stylesheet/less" type="text/css" href="less/ groundedcornersmixins.less" />.
Note that this code leaves out the general styling of the div and body tags in the HTML. These styles are only used to make the demo look good and do not actually demonstrate Less in any useful manner. After rewriting your Less code, reload your browser or watch it if you have applied the #!watch trick. You will see that the output will be exactly the same. This shows you how to get the same results with Less using a more efciently structured code.
[ 24 ]
Chapter 1
CSS resets overwrite the default styling rules of the browser and create a starting point for styling. This starting point looks and acts the same on all (or most) browsers. In this book, normalize.css v2 is used. Normalize.css is a modern, HTML5-ready alternative to CSS resets and can be downloaded from http://necolas.github.io/ normalize.css/. It lets browsers render all elements more consistently and makes them adhere to modern standards. To use a CSS reset, you can make use of the @import directive of Less. With @import, you can include other Less les in your main Less le. The syntax is @import "{filename}";. By default, the search path for the directives starts at the
directory of the main le. Although setting alternative search paths is possible (by setting the path's variable of your Less environment), it will not be used in this book. The example Less les in this book will contain @import "normalize.less"; in the rst few lines of the code. Again, you should note that normalize.less does contain the CSS code. You should pay particular attention to the prots of this solution! If you want to change or update the CSS reset, you will only have to replace one le. If you have to manage or build more than one project, which most of you should be doing, then you can simply reuse the complete reset code.
In the next example, you can use a linear gradient of two colors. The background gradients use vendor-specic rules. You can make use of the example code from the rounded corners example to add gradients to it. The rst step is to copy or open less/gradient.less and add a new mixin at the start of this le as shown in the following code:
/* Mixin */ .gradient (@start: black, @stop: white,@origin: left) { background-color: @start; [ 25 ]
Improving Web Development with Less background-image: -webkit-linear-gradient(@origin, @start, @stop); background-image: -moz-linear-gradient(@origin, @start, @stop); background-image: -o-linear-gradient(@origin, @start, @stop); background-image: -ms-linear-gradient(@origin, @start, @stop); background-image: linear-gradient(@origin, @start, @stop); }
This will create gradients from the left (@origin) to the right with colors from @start to @stop. This mixin has default values. IE9 (and its earlier versions) do not support gradients. A fallback can be added by adding background-color: @start;, which will create a uniform colored background for older browsers.
#footer selectors as shown in the following code:
#header{ background-color: red; .roundedcornersmixin(); .gradient(red,lightred); } #content{ background-color: white; min-height: 300px; .roundedcornersmixin(20px); .gradient(); } #footer{ background-color: navy; .roundedcornersmixin(20px); .gradient(navy,lightblue); }
After adding the mixin to your code, you can call on it for our #header, #body, and
For example, if you renamed the Less le to less/gradient.less, you would have also had to change the reference in your HTML le to the following code:
<link rel="stylesheet/less" type="text/css" href="less/gradient.less" />
[ 26 ]
Chapter 1
If you now load the HTML le in the browser, your results should be like the following screenshot:
Gradients in the header, content, and footer from the example code
[ 27 ]
To make things clear, it is important to keep in mind the button that is about to be pressed. The button will have two states: pressed and not pressed. Without transitions and animations, we are enabled to style these states only. The color of the button is white, and its color becomes red when you hover the mouse over it. (In CSS terms, its state becomes hovered by adding the :hover pseudo class.) In this case, the transition describes how the hovered button becomes red. For example, the change in color from white to red in two seconds (which makes it pink halfway) shows that the start of the color change is slow and changes faster as time passes. Using animations here enables us to describe the state of the button for every time interval between the start and end. For example, you don't have to change the color from white to red, but the change covers all the states, from white, blue, green, and nally to red. Transformations change the position of an element and how it looks. They do not depend on the state of the element. Some of the possible transformations are scaling, translating (moving), and rotating. In practice, we use a combination of animations, transformations, and/or transitions in most situations. Also, in this case, vendor-specic rules will play an important role. Now, a transformation will be added to our example. Using the example code with rounded corners and gradients, copy the following code to less/transition.less or open less/transition.less and add the following code to the beginning of the le:
/* Mixin */ .transition (@prop: all, @time: 1s, @ease: linear) { -webkit-transition: @prop @time @ease; -moz-transition: @prop @time @ease; -o-transition: @prop @time @ease; -ms-transition: @prop @time @ease; transition: @prop @time @ease; }
This mixin has three variables; the rst will be the property (@prop) that you will change. This can be height, background-color, visibility, and so on. The default value all shouldn't be used in the production code as this will have a negative effect on performance. @time sets the duration in milliseconds or seconds with s appended to it. The last variable, @ease, sets the transition-timing-function property. This function describes the value of a property, given that a certain percentage of it has been completed. The transition-timing-function property describes the completeness of the transition as a function of time. Setting it to linear shows the effect with the same speed from start to end, while ease starts slow and ends slow, having a higher speed in the middle. The predened functions are ease, linear, ease-in, ease-out, ease-in-out, step-start, and step-end.
[ 28 ]
Chapter 1
Now, you can edit less/transition.less to use this mixin. You can set the background color of the body when you hover over it. Note that you don't need to use the transition to change the gradient color but rather change the background-color attribute. You are using background-color because transition-duration doesn't have a visible effect on the gradient. The code of the background-color transition is as follows:
#content{ background-color: white; min-height: 300px; .roundedcornersmixin(20px); .transition(background-color,5s); } #content:hover{ background-color: red; }
If you renamed the Less le, for example, to less/transition.less, you would also have to change the reference in your HTML le to the following code:
<link rel="stylesheet/less" type="text/css" href="less/transition.less" />
If you load the HTML le in the browser, you will be able to see the results in the browser. Move your mouse over the content and see it change from white to red in 5 seconds. Finally, a second example that rotates the header can be added. In this example, you will use @keyframes. Using @keyframes will be complex. So, in this case, you can dene some vendor-specic rules and add these animation properties to #header: as follows:
@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } } @-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } } @keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } } #header{ -webkit-animation:spin 4s linear infinite; -moz-animation:spin 4s linear infinite; animation:spin 4s linear infinite; }
[ 29 ]
You can add the preceding code to our example les or open less/keyframes.less. If you renamed the Less le, for example, to less/keyframes.less, you also have to change the reference in your HTML le to the following code:
<link rel="stylesheet/less" type="text/css" href="less/keyframes.less" />
Now, load the HTML le in the browser and watch your results. Amazing, isn't it? With a little bit of creative thinking, you will see the possibilities of creating a rotating windmill or a winking owl using only CSS3. However, the rst thing that should be done is to explain the code used here in more detail. As mentioned earlier, there are many cases in which you would make combinations of animations and transformations. In this example, you also get to animate a transformation effect. To understand what is going on, the code can be split into three parts. The rst part is @keyframes, shown in the following code, which describe the value of the CSS properties (transformation in this case) as a function of the percentage of the animation completeness:
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }
These keyframes have been given the name reference spin, which is not a special effect but only a chosen name. In the preceding example, a state of 100 percent completeness is described. At this state, the animated element should have made a rotation of 360 degrees. This rotation is the second part that needs our attention. The transformation describes the position or dimensions of an element in the space. In this example, the position is described by the number of degrees of rotation around the axis, 360 degrees at 100 percent, 180 degrees at 50 percent, 90 degrees at 25 percent, and so on. The third part is the animation itself, described by: animation:spin 4s linear infinite;. This is the shorthand notation of settings of the subproperties of the
animation property. In fact, you can write this as the following code, without the vendor-specic rules:
animation-name: spin; animation-duration: 4s; animation-timing-function:linear; animation-iteration-count: infinite;
[ 30 ]
Chapter 1
You can use these three parts to build a complete animation. After doing this, you can extend it. For example, add an extra keyframe, which makes the time curve nonlinear, as follows:
@keyframes spin { 50% { transform: rotate(10deg);} 100% {transform: rotate(360deg); } }
You can add a second property using background-color. Don't forget to remove the gradient to see its effect. This is shown in the following code:
@-moz-keyframes spin { 50% { transform: rotate(10deg); background-color:green;} 100% { transform: rotate(360deg); } } //.gradient(red,yellow);
You will have noticed that the complete prot of using Less isn't realized here. You will have to write the @keyframes denition repeatedly due to its variable animation name. In Chapter 4, Avoid Reinventing the Wheel, a solution will be provided to you for this. Unfortunately, browser support for transitions, transformations, and animations is not great and varies between browsers. Google Chrome does not support CSS 3D transforms, Firefox lacks support for CSS Filters, and IE9 (and earlier versions) don't support them at all. To solve this, many developers look to jQuery to support their animations. The jQuery.animate() function allows us to change the CSS properties of the elements using JavaScript. You can still use Less to set the initial CSS. An alternative for this will be to use animate.css (which you can access at https://github.com/daneden/animate.css); this cross-browser library of CSS animations gets converted into Less code with a jQuery fallback.
Box-sizing
The box-sizing property is the one that sets the CSS-box model used for calculating the dimensions of an element. In fact, box-sizing is not new in CSS, but nonetheless, switching your code to box-sizing: border-box will make your work a lot easier. When using the border-box settings, calculation of the width of an element includes border width and padding. So, changing the border of padding won't break your layouts. You can nd a copy of the code used in this section in boxsizing.html from the download les.
[ 31 ]
Nowadays, most web designs use a grid. Grids split your design into columns of equal size. This helps you make things clear and build responsive interfaces. Depending on the available screen size (or width), you can show your content and navigation with a different representation of the same columns. To handle different screen sizes, some parts of your website will have uid width or height. Other elements, such as borders, gutters, and the white space, should have a xed width. The combination of uid widths as a percentage of the screen width (or viewport) with xed widths becomes complex. This complexity will be due to the fact that browsers use different calculations for padding and margins of elements. In order for you to see this, look at the following example. A container of 500 pixels width has been created. Inside this container, you can add two rows and split the second row into two parts of 50 percent (or half) width.
<div class="wrapper" style="width:300px;"> <div style="background-color:red;width;100%;">1</div> <div style="backgroundcolor:green;width:50%;float:left;">2</div> <div style="backgroundcolor:blue;width:50%;float:right;">3</div> </div>
An HTML wrapper
The current structure doesn't show a problem until you add some padding, which is used to construct some space or a border between the two columns on the second row (numbers 2 and 3 in the image of the HTML wrapper). The padding and the border will break our layout as follows:
<div class="wrapper" style="width:300px;"> <div style="background-color:red;width:100%;">1</div> <div style="background-color:green;width:50%;float:left;border:5px solid yellow;">2</div> <div style="background-color:blue;width:50%;border:5px solid yellow;float:right;">3</div> </div> <br> <div class="wrapper" style="width:300px;"> <div style="background-color:red;width;100%;">1</div> [ 32 ]
Finally, the output of this code should look like the following screenshot:
A similar action can be performed, except that the wrappers can be wrapped inside an extra wrapper. The box-sizing: border-box; declaration can then be applied to this. Now, the results should look like the following screenshot:
As you can see, the padding and borders are subtracted by 50 percent from the parent. This will make the calculation a lot easier. Of course, you can do the calculating yourself once the parent container wrapper has a xed width. If the parent has 300 pixels, then 50 percent of this will be 150 pixels. Taking away the padding and the width of the border will give you the xed size of a column. This won't work when your parent has a uid width (the percentage of the viewport). Fluid layouts change their width with the width of the screen. If your screen becomes smaller, then all the elements become smaller too and the percentage stays equal. By doing calculations for all the possible screen sizes to nd the real size of a column that allows all of your elements to align, you will quickly nd this to be a long, challenging, and arduous process.
[ 33 ]
For these reasons, you should make use of box-sizing: border-box; for all the examples in this book. Please note that box-sizing has to also be dened by vendor-specic rules as follows:
-webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box;
This code has been added into a separate le called boxsizing.less. From now on, the basics of our Less les will now contain the following code:
@import: "normalize.less"; @import: "boxsizing.less";
In the following chapters, you will learn more about organizing your Less code into les.
Server-side compiling
You have taken the rst few steps towards Less development already. As explained earlier, client-side compiling has been used. However, client-side compiling with less.js shouldn't be used on real websites. This is because despite making your development easy and fast, compiling your Less les for every page request (or in fact, initial page load per user) will actually slow down your website.
[ 34 ]
Chapter 1
For the production environment, it is required that you compile your les and serve the nal CSS le to the browser. The term server side can be somewhat misleading. Server side in this context means a compiled CSS code is sent to the client's browser instead of Less code, which has to be compiled in the client's browser by less.js before it is shown. You should precompile your Less code. By copying and pasting the results of less.js to a le and including this as a CSS le in your HTML les, you should have the same effect, except that your CSS is not minimized. Less bundles a command-line compiler. Installing and using it is simple using the following command:
>> npm install -g less >> lessc styles.less styles.css
The package manager for the Node JavaScript platform is npm. Node enables you to run Java scripts without a browser. Node and npm run on Windows, Mac OS X, and other Unix/*nix machines. You will nd the Node.js source code or a prebuilt installer for your platform by visiting http://nodejs.org/download/. To install npm, please read the instructions in the README le by visiting https://www.npmjs.org/doc/ README.html. Use the help function to get a list of options you can use with the following command-line compiler:
>> lessc help
lessc styles.less styles.css compiles styles.less to styles.css. The links to styles.css in your HTML after successfully compiling it are then shown as follows:
<link rel="stylesheet/css" type="text/css" href="styles.css">
[ 35 ]
The Less command-line compiler has two options for compressing and minimizing. The rst option (-x or yui-compress) uses the YUI CSS Compressor (which you can access at http://yui.github.io/yuicompressor/css.html) and the second option (--clean-css) uses clean-css (which you can access at https://github.com/ GoalSmashers/clean-css). You cannot use both options together. Clean-css claims to be faster, and until recently, you would not have found much difference in the compression. By compiling keyframes.less from the previous example, including normalize.less and boxsizing.less, the result will have a size of 4377 bytes. With clean-css, this drops to 3516 bytes, whilst YUI gives 3538 bytes. Since Version 1.5.0 of Less, clean-css is the compiler's default option.
When choosing a GUI for Less development, always check which version of less.js it uses. Some GUI's are built on older versions of less.js and don't support the latest features. Web developers using Visual Studio should check out Web Essentials. Web Essentials extends Visual Studio with a lot of new features, including Less. Also, other IDEs such as PHPStorm have built-in Less compilers. There is a Less plugin for Eclipse also.
[ 36 ]
Chapter 1
Summary
In this chapter, you refreshed and extended your knowledge about CSS3. You learned how to compile your Less code on the client side. Furthermore, you have written the code that allows you to have rounded corners, gradients, and animations in Less, so you can now witness the prots of using Less and take the crucial initial steps to organize and plan your new projects. You witnessed why you would want to use CSS resets, how to compile these into Less code, as well as how the box-sizing border-box can make your job easier. You also saw what a mixin is, how to use it, and how you can import a Less le with the @import directive. Last but not least, you have learned what server-side compiling is and how to use GUIs. In the next chapter, you will learn how to use variables in Less and how to build and use complex mixins.
[ 37 ]
Alternatively, you can buy the book from Amazon, BN.com, Computer Manuals and most internet book retailers.
www.PacktPub.com