Page 1 of 1

Advanced CSS: The Dynamic Stylesheet Language Rate Topic: ***** 4 Votes

#1 Vip3rousmango  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 56
  • View blog
  • Posts: 98
  • Joined: 10-February 10

Posted 29 March 2011 - 07:06 PM

*
POPULAR

Introduction to LESS.js

The Dynamic Stylesheet Language


Introduction to LESS
Welcome to my second tutorial! Hope you guys find this useful, as I know this has changed the way I use CSS forever!

What this tutorial is covering today is how to add variables, mixins, nested rules and much more to CSS 3 to make it function like you have never seen before! The amount of benefits you can gain from being able to optimize your CSS could be explained here but I just won't do it justice until you see it in action. It should take you about 1-2 hours to learn the concepts presented here.

You can find an example of these concepts ----->>> HERE <<<-----


This tutorial already assumes you know how to code (X)HTML and CSS 3 and should be comfortable with creating basic layouts of pages (including header, content, sidesbars, footers and can style individual elements within containers and it's children). Knowlege of:

  • Grouping/Nesting
  • Dimensions
  • Display
  • Positioning
  • Floating
  • Align
  • Pseudo-class
  • Pseudo-element
  • Image Opacities
  • Image Sprites
  • Media Types
  • CSS Attribute Selectors


would be a big help, but not required. However, I won't be covering (X)HTML/CSS itself in this tutorial, just possibly using elements within those topics, so if you're unfamilar with them I suggest you do a little reading up! If you're unable to write CSS mark-up "on-the-fly" that's not a big deal but, you might want have a stronger base before you start manipulating it! I know I confused myself with my own projects sometimes so making a strong foundation correctly to build upon will always serve you well in the future.

So I know what you're thinking now.. "Wait a minute! You can't add variables and all this "mix-in stuff" to CSS! So what's going on here!?".

Well you're correct! Natively Cascading Style Sheets doesn't support this style of scripting but when we add a very clever Javascript libary called LESS.js we can expand CSS beyond just its normal capabilities. Check this out:

Example 1:
  // LESS

@color: #FFFFFF;

#header {
  background-color: #000000;
}

h2 {
  color: @color;
}

/* Compiled CSS in browser */

#header {
  background-color: #000000;
}

h2 {
  color: #FFFFFF;
}



That is LESS in action with CSS. Don't worry if this looks confusing, all will be explained by reading this shortly. If you already grasp the concept outlined above then you're well on your way to seeing how powerful LESS is and will help in day-to-day CSS coding.

If you already use LESS in your CSS projects then please let us know how you use it to your advantage and some of the things you've created!

LESS INFO:

LESS was developed by Alexis Sellier, more commonly known as cloudhead. I am in no way or part taking credit for LESS obviously, just showing you some really cool ways to use it in your CSS coding. You can read more information, see some of the tutorial examples and learn more about LESS.js on the --->>> official page <<<---.

***NOTE:In order to use LESS you will need to make sure your browser has Javascript turned on as your website now requires Javascript to display all styling. If you plan to use LESS for mobile development you might run into some issues with Javascript running in some browsers. We will cover a "hack" to solve this issue. But Remember that it requires Javascript to run (LESS, not the "hack")! END NOTE***

Let's begin: LESS Setup

So to acheive what we did with that #header and h2 property above, a couple of steps are needed. First we need to setup our environment to use LESS within CSS. This is very easy and can be done in a few steps.

Step 1: Download the Less.js file and add it to your project! You can get it here. The most current version as of writing (1.0.41.min) is attached Attached File  less-1.0.41.min.zip (10.49K)
Number of downloads: 845 along with the example files used. OR You can just link to it since it's hosted on googlecode like so:
<script src="http://lesscss.googlecode.com/files/less-1.0.41.min.js"></script>

Step 2: Start a blank HTML document and either make your own markup or paste the markup below to follow along. We will not be building anything of signifigance HTML layout wise, more just basic elements to help display CSS concepts required for learning, but I do have an important note to make within the <head> tags.
This would be a document for your website if it was a real project. Since we are going to be using an external stylesheet for this tutorial you need to link to your css file within the <head> of your HTML and load the LESS.js like any normal CSS stylesheet and Javascript file but their is a difference, can you spot it?:

<!DOCTYPE HTML>

<html lang="en">
<head>
<meta charset="UTF-8">
<title>LESS.js Tutorial</title>
<!-- LESS Stylesheet -->
<link rel="stylesheet/less" type="text/css" href="css/style.less">

<!-- LESS Javascript -->
<script src="http://lesscss.googlecode.com/files/less-1.0.41.min.js"></script>
</head>

<body>
	<div id="header">
		<h2>A Headline</h2>
		<p> This is some text with an <a href="#">anchor</a> present.</p>
	</div><!-- /header -->
	
	<div id="footer">
		<a href="#">Link Name</a>
	</div><!-- /footer -->

</body>
</html>


If you noticed, the rel="stylesheet/less" and the href="styles.less" are different than the normal "stylesheet/css" and styles.css respectively. In our case LESS uses a special stylesheet ending (.less) which it parses and then outputs a live stylesheet for the browser. Nifty huh!
So that means our default stylesheet has a .less ending hence the "stylesheet/less" relationship. After that, we need to import the logic for LESS locally (Option 1), or by calling it with the URL version posted in Step 1 (Option 2). DO NOT USE BOTH OPTIONS!

And that's it, now we can start using style.less to style our webpage like normal!

Using LESS #1: Variables

Our first topic is Variables. If you've ever used Javascript, PHP or any other larger scripting language sooner rather than later, you'll run into variables.

For our purpose, variables allow you to specify widely used values in a single place, and then re-use them throughout the stylesheet. This makes global changes as easy as changing one line of code! Lets use Example 1 and break it down.

Inside our style.less we can define a variable by using the @ symbol before the desired variable name and then give it any value we want. Then we call the variable inside the CSS property #header:

Example 1.2:
@color: #FFFFFF;

#header {
  color: @color;
}


Here we made a new variable @color: and it's value set to #FFFFFF. To use this new variable we made, we are going to assign it to color: by replacing the spot the color hex number (#FFFFFF) normally would of gone. If you save and refresh the page in a browser and view your CSS (I love Firebug for Firefox, or Inspect Element in Safari/Chrome) you should see:
#header {
    color: #FFFFFF;
}


This means it works! You just sucessfully made your first CSS variable using LESS.js! Cool stuff huh! So back to Example 1, it's the same concept just with more than one use. That's the beauty of variables! You can use them over and over and it can save you lots of time when you have different specific colours for specific links, nav elements, box shadows etc... but note that variables are actually ‘constants’ in that they can only be defined once. I'll let you play around with the idea and when you're comfortable with creating multiple variables and calling them in various properties we can move on.

Using LESS #2: Nested Rules

This is something I love using when marking up CSS with LESS. Rather than constructing long selector names to specify inheritance, in LESS you can simply nest selectors inside other selectors. This makes inheritance from parents much easier to visualize on a page, at least in my opinion. Check this out, this is how you should normally go about styling the paragraph in our header HTML markup:

Example 2:
#header h2 {
  font-size: 26px;
  font-weight: bold;
}
#header p {
  font-size: 12px;
  color: #FFFFFF;
}
#header p a {
  text-decoration: none;
}
#header p a:hover {
  border-width: 1px;
}


Ok nothing new here. If you wanted to target children, you have to declare the parent first, then each child element till you arrive at the one you want to style. Boring!! With Nested Rules you can write Example 2 like this:
// LESS

#header {
  h2 {
	font-size: 26px;
	font-weight: bold;
  }                                             //Close h2
      p { 
  	    font-size: 12px;
	    color: @color;
		a { text-decoration: none;
		  &:hover { border-width: 1px } //Close :hover
		  }                             //Close a
        }                                       //Close p
}                                               //Close #header


Now, when you "nest" a child element inside its parent, it takes all the styling of the parent and applies it to the children for you! Notice the & combinator. It is used when you want a nested selector to be concatenated (joined) to its parent selector, instead of acting as a descendent. This is especially important for pseudo-classes like :hover and :focus. I'll wait a second while you calm yourself from the realization of how much time you could of saved yourself on past projects using this method. Are you ok to continue now? Your sure? Okay, awesome!

Using LESS #3: Mixins (Parametric Included)

So if you're like me and other developers/designers and want your fancy CSS 3 shadows, rounded borders etc... working on all browers you know the pain of typing out all the versions for each runtime (moz, webkit, standard) so this is where Mix-In's come into play. Mixins allow you to embed all the properties of a class into another class by simply including the class name as one of its properties! Yes, I realize that sounds like a mouthful, but think of it like a variable, but for whole CSS classes. Mixins can also behave like functions too and take arguments as well, as seen below in Example 3:

Example 3:
// LESS

@footcolor: #000000;

// Create Mixin .rounded-corners and assign a @radius: variable to pass through

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

#header {
  .rounded-corners;
}
#footer {
   background-color: @footcolor;
  .rounded-corners(10px);
}

/* Compiled CSS in browser */

#header {
  border-radius: 5px;         /* This is 5px because that's the default @radius value we set */
  -webkit-border-radius: 5px; /* This is 5px because that's the default @radius value we set */
  -moz-border-radius: 5px;    /* This is 5px because that's the default @radius value we set */
}
#footer {
   background-color: #000000;
  border-radius: 10px;         /* This is 10px because we passed a value of 10px */
  -webkit-border-radius: 10px; /* This is 10px because we passed a value of 10px */
  -moz-border-radius: 10px;    /* This is 10px because we passed a value of 10px */
}


Wow lots going on here so let's break Example 3 down! The proper usage to make a Mixin is like a CSS class and Javascript function in one. Proper usage is .mixinName() {}. Looking like a CSS class but, has the power of a Javascript function.

So we want to set a border radius but only want to type out the code once. We can set a mixin to call all 3 at the same time by making one like a variable but rather than give it one value, we can assign multiple to a mixin:

Example 3.1:

//LESS

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

#header {
   .rounded corners;
}


So here we made our mixin and gave it something to output. And this would work for our Example 3 /* Compiled CSS in Browser */ result for #header but we want more control over the border-radius and we don't want to make a different mixin for each different radius size so we can give the mixin an arguement to pass through to our styling:

Example 3.2:
//LESS

.rounded-corners(@radius: 5px;) { // 1) We create our new variable inside the Mixin
border-radius: @radius;           // 2) We then Add the Variable where it needs to appear to affect the styling
-webkit-border-radius: @radius;
-moz-border-raidus: @radius;
}

#footer {
   background-color: @footcolor;
   .rounded-corners(10px);
}


Now we have a Parametric Mixin! This would output the #footer result from Example 3 /* Compiled CSS in Browser */ above. By passing the 10px as the mixin's arguement you can effectivly alter the created variable to your liking! You will use Mixins often if you choose to use LESS so this concept is particularly important. Try it out and play around with them to learn how they work.

Using LESS #4: "Live Refresh"

This is our last topic we're going to cover in this tutorial and is a litte known function of LESS. You can make the browser refresh automatically (locally) without having to continually hit the refresh button while styling! All you need to do is add:
<script>
less.env = 'development';
less.watch();
</script>
</body>


To your HTML markup just before the closing </body> html tag, refresh the page and that's it! Now your page will refresh anytime you make a change live to style.less! Pretty cool huh? Make sure you TAKE THIS OFF before you deploy your solution though! Great for development, not for live usage.

Final Thoughts:
I hope you've enjoyed this introduction to the LESS.js Libary and what it can do to extend the functionality of your CSS markup. I hope to see many sites in the future using this moving forward to bring complex CSS and creative design styles to life!

This is what your final HTML and CSS markup should look like.
Final index.html Markup
<!DOCTYPE HTML>

<html lang="en">
<head>
<meta charset="UTF-8">
<title>LESS.js Tutorial</title>
<!-- LESS Stylesheet -->
<link rel="stylesheet/less" type="text/css" href="css/style.less">

<!-- LESS Javascript -->
<script src="http://lesscss.googlecode.com/files/less-1.0.41.min.js"></script>
</head>

<body>
	<div id="header">
		<h2>A Headline</h2>
		<p> This is some text with an <a href="#">anchor</a> present.</p>
	</div><!-- /header -->
	
	<div id="footer">
		<a href="#">Link Name</a>
	</div><!-- /footer -->

<!-- Dev Purposes Only -->
<script> 
less.env = 'development';
less.watch();
</script>
</body>
</html>


Final CSS.less Markup:
@color: #FFFFFF;
@footcolour: #000000;

body {
	background-color: @footcolour;
}

#header {
	background-color: #000000;
}

h2 {
	color: @color;
}

#header {
  h2 {
	font-size: 26px;
	font-weight: bold;
  }                                     //Close h2
  p { 
  	font-size: 12px;
	color: @color;
		a { text-decoration: none;
		  &:hover { border-width: 1px } //Close :hover
		}                               //Close a
  }                                     //Close p
}                                       //Close #header


// Create Mixin .rounded-corners and assign a @radius variable to pass through

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

#header {
  .rounded-corners;
}
#footer {
   background-colour: @footcolour;
  .rounded-corners(10px);
}


Enjoy LESS/CSS and happy coding!

P.S. The Mobile "Hack"
What, you thought I forgot?! Ha!

So, you want to use LESS but you're thinking of doing going mobile friendly, or you have a website already and want to make it compatible for mobile browsing?

Well, I'd start by telling you that using LESS would probably not be your best idea since you'll require Javascript to be enabled by default on a mobile browser which means your limiting yourself to smartphone users only (not that 220 million users in North America alone is small, but you get the point) if you're trying to maximize accessability.

If you have a website that has a re-direct via some type of CSS/Javascript mediatype detection, or redirect where it sends you to a whole seperate subdomain/site folder/something that doesn't require access to the original stylesheet of the main (or root) website then you could use LESS for your main site and just use an normal stylesheet for your mobile portal.

This second method is our "hack" which, to be honest isn't a hack at all really, just good ol' fasion copying the output of the style.less (from the browser, I used Firebug extension in Mozilla Firefox personally) and pasting into a fresh .css stylesheet which you <link> for your mobile site. Then you can edit it down on your own to make it approprate to display into mobile browers as just pasting the output will give you exactly the same stylesheet as your main website, not a mobile portal.

Enjoy!

Attached File(s)



Is This A Good Question/Topic? 12
  • +

Replies To: Advanced CSS: The Dynamic Stylesheet Language

#2 Vip3rousmango  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 56
  • View blog
  • Posts: 98
  • Joined: 10-February 10

Posted 30 March 2011 - 06:13 AM

Had some issues uploading the source files, the .zip given in the Tutorial ONLY contains LESS.js libary.
Here are the source HTML/CSS files to accompany anyone wanting them for reference.

Attached File  LESS Tutorial Source.zip (1.16K)
Number of downloads: 219
Was This Post Helpful? 1
  • +
  • -

#3 Toxicterror  Icon User is offline

  • blub

Reputation: 15
  • View blog
  • Posts: 687
  • Joined: 10-March 09

Posted 20 April 2011 - 01:24 AM

Why cant plain CSS be like that :)
Great tutorial and introduction to LESS. Definitly will use it :D
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1