Different ways to add CSS styles to an HTML Page

On 11/13/2013
Hi, in this post we’ll see how to add CSS styles to the HTML pages.  Say we want to set margins for a page.  If we want the top & bottom margins to be of 10 pixels and left & right margins of 5 pixels, then here is the css code:

body{
   margin-top: 10px;
   margin-right: 5px;
   margin-bottom: 10px;
   margin-left: 5px;
}


It can also be rewritten in a single line as,

body{ margin: 10px 5px 10px 5px; }

The order of margins will be as top, right, bottom and left margin resp.

Ok. Done.  But how we are going to incorporate this in our html page? It’s simple.  There are different ways to add the css styles to an html page.

Method One: Inline


In this method, the styles can be added directly to the html tags itself.  And it can be used only if we want to apply a style for single occurrence.  It can be added to any html tags using the style attribute.

<!DOCTYPE html>
<html>
<head>
</head>
<body style=”margin: 10px 5px 10px 5px;”>
Hello World!
</body>
</html>

Note: Generally it’s not a good practice to add inline styles.  It will become a real headache when we want to update the styles to the websites in future.

Method Two: Internal


In this method, the styles can be added using the <style> element within the <head></head> section of a page.  The styles will be relevant only to the html page they are added.

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body{
 margin: 10px 5px 10px 5px;
}
</style>
</head>
<body>
Hello World!
</body>
</html>

Method Three: External


We can create a separate css file and link it to the html pages using the <link> tag.  Similar to method two, this tag should be placed within the <head> </head> section of an html page.  It is the most effective method as we can incorporate a common style to all the pages in a website by linking a single css file.  Future updates to the styles will be relatively easier as we have to make changes to the css file alone rather than updating all the html pages in our website.

CSS Code File:

body{
   margin: 10px 5px 10px 5px;
}

Just place the above code in a file and save it as “style.css”.  Now include this one in the html file as given below and load the html page in the browser.  You can add as many styles as required to a single css stylesheet.

HTML Code File:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
Hello World!
</body>
</html>

The “href” is an attribute of the <link> tag that tells the browser, which stylesheet to be used to render the particular html page.

Note:  Store the css file with in the same folder in which you have the html file.  In case you store css file in separate folder, ensure you give the correct path to the css file while linking.

No comments:

Post a Comment

Contact Form

Name

Email *

Message *