Mixins In JavaScript

What is a Mixin?

Original concept of mixin came from an ice cream shop that provided on-demand customizable ice cream. At these shops, customers can make their own flavor by mixing up different toppings. You would pick up an ice cream flavor and a bunch of toppings, and then you can choose to mix them inside the ice cream by smashing these together instead of sprinkling as a topping. Hence, these are called mixins.

In terms of programming, Mixins are these pieces of code that you can mix with other objects to extend their functionality. Basically, you can borrow features from different mixins to compose the kind of object you desire.


Inheritance vs Composition

By using mixins, you can compose objects with a desired functionality. This is very different from using inheritance, which is much rigid and doesn’t work most of the time when you want to create dynamic ever-changing models. For example, you want to build a class called javaScriptEngineer, where javaScript means you can code in JavaScript and related technologies and Engineer means you have some sort of Engineering degree. Instead of using inheritance, where you would create an engineer class and extend it to make a JavaScript engineer, you can separate out both the functionalities into a separate mixins. You can compose javaScriptEngineer by using the Object.assign() method where you can borrow methods from two different mixins.

Composing Object using Mixins

In the following example, we have two objects jsSkill and degree, they both would serve as mixins when I combine their properties and copy into an empty object using the Object.assign() method. The newly created object jsEngineer will have functionality of jsSkill and degree. Similarly, you can create a fullstackEngineer by using one more mixin. Since Fullstack engineer knows JavaScript, has an engineering degree, and also knows one or more backend languages, we just need to add an additional backendSkill mixin. This allows us to compose a fullstackEngineer.

Factory Functions

Factory functions are functions that produces objects. In JavaScript, there are two ways to create objects, one by using either function constructors or classes. In either case, you have to use a new keyword. And secondly, by using regular functions. When you use regular functions to build objects, they are called factory functions. Following example describes a factory function.

Factory Function with closures

Having an inner variable inside the factory function will maintain the state inside a closure. The state will be stored inside every function that is using the variable.

Function Mixins

Using a factory function with closures you can build function mixins. Each mixin would take an Object as a parameter and returns a new object that would take passed object and extend it with mixin’s functionality. Here is an example of building an object called superman using two mixins humanFactory and flyFactory. superman has characteristics of a human so he has an ability to cry, however unlike humans, he can fly. So, combining two different kind of abilities we can transform an ordinary reporter clark kent into the superman.

Note: When you pass an empty object to this factory, the returning Object would have a functionality of humanfactory, flyFactory and their preserved states.

Conclusion

function mixin is one of the functional programming paradigm . Mixins help you reduce repetition of functions and promotes the reusability. This can reduce maintenance. It also support encapsulation using closures, with ability to inherit private data. In a way you can sort of achieve multiple inheritance since can inherit from multiple mixins. In this article, we discussed function mixins for a functional programming paradigm. The same concept also applies to ES2015 classes with a difference in syntax. To understand mixin for ES2015 classes, click here -> (class mixins coming soon).

JavaScript Classes

Class Keyword

JavaScript uses the class keyword, which was introduced in ES2015. Prior to ES2015, you can create objects by using function constructors and prototype inheritance. There are many developers who believe that classes do not belong to JavaScript. They consider JavaScript as a functional programming language. I have heard opinions from the other side of the isle, where they believe that classes provide a less complicated solution. So regardless of an individual’s belief, classes are here! They are here to stay and are used extensively in modern frameworks like Angular, React, and Ember. Before we go deep into classes, let’s understand what does a class mean to JavaScript.

Feels like Classes, Smells like Classes!

Introduction to classes in JavaScript was a great news for some, especially, former Java programmers who will feel like home. I believe, objective of people who added classes was just the same. However, I think a Java programmer will be more confused because under the hood classes do not act the same way as they do in Java. To quote a simple analogy, it’s like when you want your kids to eat more vegetables, you make a pizza, substitute tofu for cheese and spinach for pepperoni. Though you hide spinach in the middle layer, your kids can recognize that this is not a real pizza in their very first bite! Java programmers may feel the same as classes in JavaScript internally use the same function constructor and prototype methods from the versions prior to ES2015. Said that, syntactically classes are defined in the similar way as they are defined in Java.

Syntax

In the example bellow, we have defined class Car. Notice the difference between the function declaration and class declaration? While declaring a class, we do not use semicolon. Similarly, to define a constructor, use the keyword ‘constructor’ and add the parameters to set the initial properties. If you check the type of the class you will be surprised that it’s actually “function” not “class”.

 Inspecting  a JavaScript Class
Inspecting a JavaScript Class

If you inspect the newCar object in detail you would see similar structure when you create object with function constructor. The only difference is that the constructor displays the keyword “class”.



Simulating Class with Function Constructor

You can simulate the class behaviour using a function constructor wrapped inside an Immediately Invoked Function Expression (IIFE). This is obviously to see what is going on inside when you define a class.

Inspecting Function Constructor
Inspecting Function Constructor

Adding Methods

Now let’s add a drive() method to class Car. Note that there is no comma between two methods. It feels weird if all you have used is JSON Objects.

Inspecting Class Method
Inspecting Class Method

When you inspect the class Car, you would notice the prototype property. Expanding prototype property displays the drive method. This means that Car is actually a function and drive is its prototype methods. Sounds familiar ? :). As I said, Class keyword is nothing but what some call “syntactic sugar”. All the methods are public. Unlike java, JavaScript doesn’t provide a way to add private methods.

Next, let’s build objects from class Car. The syntax is similar to what we used with function constructors, using the new keyword. You can execute the method on this object by calling redCar.drive().

Object.setPrototypeOf() Method JavaScript

There are two camps in JavaScript, one who uses function constructors to create objects and one who directly uses object literals. In JavaScript, function constructors can be extended by using the Object.create() method. This method lets you set prototype of one object to another object.

Constructor2.prototype = Object.create(Constructor1.prototype);

Extending Object Literals

Object literals don’t have prototype property. So, if you want to inherit properties of one literal to another, you can do it several ways. Prior to ES2015, you had to write your own extend method that would copy methods from one object to another. ES2015 introduced few new methods that makes this process easier. The setPrototypeOf() method is one of such methods.

Syntax

Object.setPrototypeOf(targetObj, sourceObj);

Here, targetObj is what you are setting prototype to from sourceObj. This method essentially sets a reference to sourceObj’s methods to targetObj’s __proto__. To understand the utility of this, let’s take two objects, toyota and camry. toyota has a drive() method. Setting the camry’s prototype to toyota makes toyota’s drive() method automatically available to camry. This is done by setting its reference in camry’s __proto__ property.


let toyota = {
  drive() {
    return 'driving toyota';
  }
}

let camry = {
  wifi() {
    return 'using wifi';
  }
}

// Set toyota's __proto__ to camry's  __proto__'s  __proto__
Object.setPrototypeOf(camry, toyota);

console.dir(camry); //prints the camry object
console.log(camry.wifi()); // using wifi
console.log(camry.drive()); // driving toyota

Object.setPrototypeOf()

If you inspect the camry object, you can view the __proto__ property and the reference to the drive() method of toyota. Since the setPrototypeOf() method sets a reference, any changes to toyota’s properties is automatically accessible to camry.

let toyota = {
  drive() {
    return 'driving toyota';
  }
};

let camry = {
  wifi() {
    return 'camry';
  }
};

// Set toyota's __proto__ to camry's  __proto__'s  __proto__
Object.setPrototypeOf(camry, toyota);

// Add a new Method to toyota object
toyota.newMethod = function() {
  return 'new method from toyota';
};

console.log(camry.newMethod()); // Prints 'new method from toyota' 



If you have a method with the same name in both the targetObject and the SourceObject, the method in the targetObject would have higher precedence. This is because javaScript first looks for object’s own method before looking into it’s prototype.

let toyota = {
  drive() {
    return 'driving toyota';
  }
}

let camry = {
  drive() {
   return 'driving camry';
  }
}

Object.setPrototypeOf(camry, toyota);
console.dir(camry.drive()); // logs "driving camry"

Super keyword

You can call the method of the sourceObject from the targetObject’s method by using the super keyword.

let toyota = {
  drive() {
    return 'driving toyota';
  }
}

let camry = {
  drive() {
   return `${super.drive()} camry`;
  }
}

Object.setPrototypeOf(camry, toyota);
console.dir(camry.drive()); // logs "driving toyota camry"

Avoid setting __proto__ manually

Prior to ES2015, Object.prototype.__proto__ was used to set the prototype of object literals. You can still use it as shown in the below example. However, it’s not recommended.

let toyota = {
  print() {
    return 'toyota';
  }
}

let camry = {
  printMe() {
    return 'camry';
  }
}

camry.__proto__ = toyota;

console.dir(camry.print());

Object.create method JavaScript

In JavaScript, Prototype inheritance is much easier than you would have imagined. Simply understand the fundamentals, like we always do!

Inheritance in JavaScript is prototype-based. Every constructor has a property called prototype. For more information about the basics of prototypes, click here.

Master constructor object ‘Object’

Object is the master constructor in JavaScript. Don’t forget to take a note of the capitalization of letter ‘O’ in Object. It’s a
function constructor. Directly or indirectly, every object is created by using Object (master object). Since, it is available in the global space, you can access it directly. If you console.dir(Object), you can view all methods that are available to Object. One of the methods is create(). It enables prototypal inheritance in JavaScript.

console.dir(Object);

Object.create Method

Syntax

Object.create(prototypeObject, propertiesObject);

The Object.create method takes two arguments. First argument must be either an object or null. The second argument is optional and used to set properties. These properties are set in object’s prototype.

Creating Objects

const myObject = Object.create(Object.prototype);
console.dir(myObject);

In the above example, the myObject object is created by using Object’s prototype. This means myObject’s creator is Object.prototype. If you inspect myObject, you can view the following:
Inspecting Object
myObject does not contain anything. However, its __proto__ property is a reference to the Object’s prototype. Hence, you can call methods on myObject that are available in Object’s prototype. If you create an object literal by using const myLiteral = {};, it possesses the same __proto__ because internally every object’s __proto__ is set to Object.prototype.To create an object without setting its __proto__ reference to Object.prototype, pass null as an argument. To verify this, inspect the object. As shown in the image below, it does not contain __proto__ property.

const myObject = Object.create(null);
console.dir(myObject);

Object.create(null)

The Object.create() method also creates objects from constructors. It is similar to using the new keyword. The only difference is that by using the new keyword, you can run the constructor. Hence, it will set the initial properties in the constructor. Whereas, the Object.create() method doesn’t run the constructor and hence the initial properties are not set.

const Car = function(color) {
  this.color = color;
};

let car1 = new Car('red');
let car2 = Object.create(Car.prototype);

console.dir(car1);
console.dir(car2);

New vs Object.create

Extending a Constructor

The main use of the Object.create() method is to extend the constructor. This means that you can inherit methods from a constructor’s prototype properties to other constructors. To extend a constructor, set a prototype reference of one object to another by using the Object.create() method.
Note: Only the constructor’s prototype is inherited and not the constructor.

const Car = function(color) {
  this.color = color;
};

Car.prototype.getColor = function() {
  return this.color;
}

const ToyCar = function() {};

ToyCar.prototype = Object.create(Car.prototype);

const legoCar = new ToyCar();

console.log(legoCar);

Object.create



Verifying Prototype

In the above example, ToyCar’s __proto__ is set to Car and Car’s __proto__ is set to Object. The isPrototypeOf method verifies if legoCar, which is originally created by using the ToyCar constructor, is a prototype of ToyCar, Car and Object. The instanceof operator also performs the similar task.

const Car = function() {};
const ToyCar = function() {};

ToyCar.prototype = Object.create(Car.prototype);

const legoCar = new ToyCar();

// Using the isPrototypeOf method
console.log(ToyCar.prototype.isPrototypeOf(legoCar)); //true
console.log(Car.prototype.isPrototypeOf(legoCar)); //true
console.log(Object.prototype.isPrototypeOf(legoCar)); //true

// Using the instanceof operator
console.log(legoCar instanceof ToyCar); //true
console.log(legoCar instanceof Car); //true
console.log(legoCar instanceof Object); //true

Conclusion

In the classical inheritance, you can create a subClass from a superClass. The subClass inherits all methods of the superClass. In JavaScript, a subConstructor inherits all methods from a superConstructor by using the Object.create method. Contrary to the classical inheritance, where methods of superClass are copied to subClass, JavaScript uses a prototype reference to access methods from the superConstructor.

JavaScript Prototype Explained

Every constructor function has a property called prototype. You can add properties and methods to it. Using a constructor function, When you create a new object, the object has access to prototype methods.

Sample code:

let Car = function(color) {
 this.color = color;
};

Car.prototype.getColor = function() {
 return this.color;
};

let redCar = new Car('red');

console.dir(redCar);

If you inspect the redCar object, you will see the following.Inspect ObjectIn the above image, the getColor() is not a part of the redCar object. There is another property called __proto__, which is set automatically. You can think of __proto__ as the creator of redCar. If you expand __proto__, the getColor method and the constructor are displayed. Constructor is the a reference to the Car Constructor that created redCar.
__proto__ property If you expand the Car constructor, the prototype property of the constructor is displayed. If you further expand the prototype property, the getColor method is displayed.

ProtoType Property JavaScriptThe getColor method from __proto__ is actually a reference to the one you added to the constructor’s prototype. It looks tricky, however, all you care about is that __proto__, the creator of redCar, has the getColor method. Hence, when you call the redCar.getColor() method, JavaScript will look inside the redCar object. If the method doesn’t exist in the object, it will look for the method in the object’s creator, which is __proto__. It will find it and execute it.
JavaScript Master ObjectSo, let’s analyze a little more and discover how is __proto__ created. If you further expand __proto__, you will see its creator, which is the master __proto__. This is basically a master object called Object (the letter ‘O’ is capitalized). Every object in JavaScript is created from Object. It also has some methods. One of the methods is toString(). When you call this method on redCar, JavaScript will first search for this method in the redCar object. If it can’t find it there, it keeps searching for the method all the way to the end of the prototype chain.




There are pros and cons of using prototype inheritance. The best part is, the inheritance makes objects lighter. The drawback is that every time you call a method that is not a part of the object, it looks for the method up the prototype chain. Hence, it makes it a little slower. The workaround is, if you are going to call this method frequently, store it in a variable to avoid the lookup.

let toString = Object.toString;
console.log(redCar.toString());

Overwriting Object Methods

If you want to customize the toString() method, you can add it to the object’s prototype. However, there are times when you want to make method available to every object. In such case, add it to the master object’s prototype. This would shadow the native toString() method.

Object.prototype.toString = function(){
    return `color:${this.color}`;
};

let Car = function(color) {
  this.color = color;
};

Car.prototype.getColor = function() {
  return color;
};

let redCar = new Car('red');


console.dir(redCar.toString());

In next article, I will show you how to use Object.create() method to set prototype of one object to another. Follow the link below. Object.create() method

JavaScript Function Constructors

It is very important to understand how JavaScript function constructors work before we move to higher level topics of Object Oriented JavaScript. In this article, I am not going to explain about the JavaScript class constructor. Instead, I’ll explain about ‘function’ constructors.
The ultimate objective of Object Orient Programming is to create objects with ease. Languages like Java have classes and each class can have a constructor, and its job is to set initial properties of the object. In JavaScript, you can create an object by directly using constructors. JavaScript lets you use a function as a constructor, if called in a specific way. And, that’s what this entire article is all about!

Usually, the job of a function is to run a specific job. Let’s say, I want to add two numbers. will write a function that takes two arguments and return the addition of the two numbers.

Sample of a function for adding two numbers:

let add = function(number1, number2) {
 return number1 + number2;
};

let sum = add(1, 2);

Now, let’s look at an example of a function constructor.

let Car = function(color) {
 this.color = color;
};

let redCar = new Car('red');

As shown in the above example, a regular function takes arguments. It performs an action within the body of the function and returns the result. A regular function may or may not return anything.
Function constructor, on the other hand, accepts color as an argument and sets it to its this.The constructor function does not contain a return statement. Instead, it returns a new object with the property that is passed as an argument.

The basic syntax difference for executing a regular function and a constructor function is the usage of the new keyword.

If you were to manually create an object without using the constructor function, the syntax will look like following:

let redCar = {
 color: 'red'
};

If you inspect the newly created object in a browser, this is how it would look like:


JavaScript function constructor inspect

As you can notice, it has a color property which is set to ‘red’; The property, __proto__, is its creator. If you expand the __proto__, you will see the following:

JavaScript function constructor inspect

The reference to the constructor that set the initial property is the Car constructor that you used to create redCar.

Drawbacks of not using new

Now, let’s consider a scenario where you execute a constructor function as a regular function without using the keyword ‘new’.

let Car = function(color) {
  this.color = color;
};

let redCar = Car('red');

In this case, this.color = color will create a new property color in the global space. You can verify the result by using console.log(window.color);

To prevent such error, add se use strict, which throws the following exception:

error calling function constructor without 'new' keyword

You can also use the new.target to throw a customized error message..

let Car = function(color) {
  if (!new.target) throw 'Car() must be called with new';
  this.color = color;
};

let redCar = new Car('red');

Private Vs Public properties

In JavaScript, all object properties are public, which means you can access it directly. For example, redCar.color. JavaScript does not have a native support for private property. Private properties are the properties you cannot access directly by using a dot notation. However, you can call a getter or have a getter method like getColor to access it and use closure.

let Car = function(_color) {
  this.setColor = function(color){
    _color = color;
  }
  this.getColor = function() {
    return _color;
  };
};

let redCar = new Car('red');

console.log(redColor.getColor());

Here _color is a private variable that cannot be accessed by the object using redCar._color.
Since it is a closure, the methods have access to them.

Adding methods to a Constructor

Best way to have methods is to set methods in prototype space. For more information about settings methods in the prototype space, go to Prototype.

Sass CSS Tutorial for beginners

Sass stands for  Syntactically Awesome Stylesheet

File extension for a Sass file is “.scss”,  which stands for Sassy CSS. “.sass” is also a valid extension for Sass with bit concise syntax.  In this article, we will only look at the latest version which is SCSS.

Why Sass?

Sass is a preprocessor that gives you a little better way of writing styles where you can have features such as nesting that are missing from CSS. In nutshell, you can write a sort of object-oriented styles by using Sass. Sass compiler converts “.scss” files to “.css” files. Since you do not need to edit CSS files directly,  you can avoid some of the mess that CSS files may create.

Code Example

[Look at the SCSS example below. Click the SCSS tab to see the SCSS code, and then from the lower-right, click View Compiled. This way, you can toggle between SCSS and compiled CSS]

The following SCSS has an ID called main, and within that there are two nested elements a and h2.  When you click View Compiled, it produces CSS that creates a style for each element. This is a basic example of how SCSS works. You can modify the example and check the result in the Result tab.


See the Pen Flat minion by Hemil Patel (@codepatel) on CodePen
1

Comments

There is a need for writing Sass specific comments that describes some of the rationals which is called Sass comments. When Sass compiler compiles down to normal CSS, the comments mentioned in Sass do not carryover to CSS.

Sass  comment :   // This is Sass Comment [Note: This is not valid in CSS]

CSS comment :  /* This is CSS Comment with opening and closing */


See the Pen Flat minion by Hemil Patel (@codepatel) on CodePen
1

Variables

Variables are very useful features of Sass.  For example, you can define a variable for a color and use it for various styles. The advantage is that when you have to replace a color with a new color, you do not need to change the color throughout the style. You only make a change to the variable value. To define a variable, add a prefix $.  See the example below.

$hcolor = red;

h2{

color: $hcolor;

}


See the Pen Flat minion by Hemil Patel (@codepatel) on CodePen
1

CSS align elements horizontally center

CSS align elements horizontally center

Let’s understand what we are trying to do here. We want to center an element horizontally within the parent element so that we would have an element placed at an equal distance from either sides.

CSS ALIGN HORIZONTALLY

There are two different ways we can align an element. The option depends on the display property of the element you are trying to place.

  • Center the element by using its own CSS – display:block;
  • Center the element by using parent element’s CSS – display:inline*
    *display:inline, display:inline-block; display-inline-flex;

1) Blocks

css block element
css block element

Elements with “display:block” property are blocks. When no width is specified, blocks occupy the entire width of the parent. In such case, there is no need to center these elements. When the width is specified, blocks would left align, by default.  You can center them by setting the left and right margins left to auto, respectively. In this case, you are adding style to the element and not the parent container. See the example below:

 


See the Pen Flat minion by Hemil Patel (@codepatel) on CodePen
1

2) Inline-* elements

css inline element
css inline element

Elements with”display:inline”, “display:inline-block”, and “display:inline-flex”,  property are the inline elements. Since, you have multiple inline elements within the same row, the horizontal centering has to be done from the parent container and not by the element itself. This is done by adding style “text-align:center” to the parent container. See the example below:


See the Pen Flat minion by Hemil Patel (@codepatel) on CodePen
1

[contact-form-7 id=”69″ title=”Contact form 1″]

Introduction to css

Introduction to css ( Cascading Stylesheet )

In webpage development, the inline style lines are responsible for formatting HTML elements.

For example in last tutorial we looked at the example Make me italic

[code language=”HTML”]<i>Make me italic</i>[/code]

Here the tag converts its content to Italic font.

Inline Styling

You can also stylize text this way using style attribute:

[code language=”HTML”]<p style=“text-formate:italic”>Make me Italic </i>[/code]

Output: Make me Italic

This works well however, it is usually not good practice to use formatting directly in the HTML file.

For example let’s say you also want the color of the text to be red

[code language=”HTML”]<p style=“text-formate:italic;color:red;”>Make me Italic </p>[/code]

Output: Make me Italic

More styles like making the text bold can be done this way:

[code language=”HTML”]<p style=“text-formate:italic;color:red;font-weight:bold”>Make me Italic </p>[/code]

Output: Make me Italic

It may not be conducive to have that many lines of style written into your HTML. It soon becomes illegible. This is alright if you can manage it, but there are other ways to make this less of an issue.

For example if you have three paragraphs and they all have the same style you can do the following:

[code language=”HTML”]
<p style=“text-formate:italic;color:red;font-weight:bold”>Paragraph 1 </p>
<p style=“text-formate:italic;color:red;font-weight:bold”>Paragraph 2</p>
<p style=“text-formate:italic;color:red;font-weight:bold”>Paragraph 3 </p>
[/code]

As you can see using style the attribute you have to repeat the same style three times. What’s worse is when you have 100 paragraphs where you want to apply the same style. Now, imagine you do all the work by adding the style to each paragraph as above and your boss ask you to change the font from italic to normal. This is where CSS comes to rescue!

Instead of writing inline style for each element move the style to a separate file with extension (.CSS)

intro to css3
html and css link reference

In HTML you can use tag-name or you will have to provide an attribute hook such as “id” or “class” and in the CSS you would refer to the hook to style that element. In the example below you can see the paragraph element has an attribute hook id with value “thisP” and in CSS using that hook you can color the font red. # (Pound sign) is called a css selector for id. In the next post we will discuss css selectors in detail.

HTML file ( Only showing what goes within body tag) :

[code language=”HTML”]
<p id=“thisP”> Using CSS<p>
[/code]

CSS file :

[code language=”CSS”]
#thisP{
color:red;
}
[/code]

Output:
Using CSS

 

 

[embedplusvideo height=”360″ width=”640″ editlink=”http://bit.ly/1qR8jZ6″ standard=”http://www.youtube.com/v/o1GdsNVYDHA?fs=1″ vars=”ytid=o1GdsNVYDHA&width=640&height=360&start=&stop=&rs=w&hd=0&autoplay=1&react=1&chapters=&notes=” id=”ep1903″ /]

HTML Style Attribute

[embedplusvideo height=”360″ width=”640″ editlink=”http://bit.ly/XiUBHz” standard=”http://www.youtube.com/v/UR3-QUTsADg?fs=1″ vars=”ytid=UR3-QUTsADg&width=640&height=360&start=&stop=&rs=w&hd=0&autoplay=1&react=1&chapters=&notes=” id=”ep1968″ /]

HTML Style Attribute

Style is an attribute in HTML

Attributes are nothing but key value pairs that go in the opening tag of an html element.

[code language=”HTML”]<tagname key=“value”>content</tagname>[/code]

In nutshell, style helps you paint HTML elements on the page. It helps you to place it in a specific location, and aids in drawing it on the page as per your aesthetic need.

Using style ,you can change font, background, border, and styles of an element.

Here is an example of how to change background color of a paragraph:

[code language=”HTML”]<p style=“background-color:red;” > blah </p>[/code]

The value of the style in above example is “background-color:red;”. You can split this into two parts; style-name and style-value separated by “:”.

The above line can be abstracted it like this:

[code language=”HTML”]<tagname style=“style-name:style-value; ”> content </tagname>[/code]

You can apply multiple styles to a single element. So let’s say if you want to add background color and font size to a paragraph, you can do following:

[code language=”HTML”]<p style=“background-color:red;font-size:30px;”> blah </p>[/code]

The above line can be abstracted it like this:

[code language=”HTML”]<tagname style=“style1-name:style1-value; style2-name:style2-value;”> content </tagname>[/code]

Inline-styling

When you use style attribute to write style directly into the opening tag it’s called inline-styling.

Issues with inline-styling:

Hard to read

Let’s look at following example where I am adding 5 styles to an element. As you can see it looks cluttered and hard to read.

[code language=”HTML”]<p style=“background-color:red;font-size:30px;font-weight:bold;border-style:solid;”> blah </p>
[/code]

Redundancy

If you have three paragraphs in a document and they all should have the same style. Using inline-styling you have to replicate the style for each paragraph.

[code language=”HTML”]
<p style=“background-color:red;font-size:30px;font-weight:bold;border-style:solid;”> blah 1</p>
<p style=“background-color:red;font-size:30px;font-weight:bold;border-style:solid;”> blah 2</p>
<p style=“background-color:red;font-size:30px;font-weight:bold;border-style:solid;”> blah 3</p>

[/code]

Now imagine the maintenance nightmare when someone asks you to change font size. You would have to change each individual paragraph. The following shows a simple example; let’s say you are writing a huge HTML document where you have 100 paragraphs. Now, imagine creating a style for each one of them.

The solution to this problem is Cascading Style Sheet (CSS)

CSS ( Cascading Style Sheet )

In the above example you have three paragraphs, we are going to remove the style attribute and replace it with class attribute “firstcss”.

[code language=”HTML”]
<p class=“firstcss”> blah 1</p>
<p class=“firstcss”> blah 2</p>
<p class=“firstcss”> blah 3</p>
[/code]

You will have to create another file with the .css extension, there you will use class “firstcss” and give it a style like this:

[code language=”CSS”]

.firstcss {
background-color:red;
font-size:30px;
font-weight:bold;
border-style:solid;
}

[/code]

In the above statement “.” is a class selector hence “.firstcss” means “class firstcss”. Looking at the overall picture, in any HTML file you write your elements with class attributes and in your .css files you give that class style. As a last step you will have add reference to the .css file in the header of your HTML file.

[code language=”HTML”]

<html>
<header>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<header>
<body>
</body>
</html>
[/code]

intro to css3
html and css link reference

You can write CSS directly into the HTML file however, as good practice always create a separate .css file.

In the next tutorial we will learn about various selectors in .css files.

[subscribe2]