Friday, July 17, 2009

CSS margin with example.

To understand margin let's start a general example and see how it display in the browser. Copy the following code and see from browser,

<html>
<body>
In this blog http://arjudba.blogspot.com you will
see there is some space (though a very little amount)
all around. But there is no space whenever you
will disply this html code inside your browser.
<blockquote>

But there will be some spaces all around this
blockquote. Both left, right, top, bottom side.

</blockquote>
You are recommended to join http://arju-on-it.com/forum
and discuss your problems there
</body>
</html>


If you run above html code, you will see all around of blockquote text there is space. But don't have control how much space will be all around. In CSS, this space is called "margins" and margins are controlled by four properties, margin-left, margin-right, margin-top and margin-bottom. We can minimize space around blockquote by following css code,

blockquote {
margin-top: 1em;
margin-right: 0em;
margin-bottom: 1em;
margin-left: 0em;
}

We can shorthand margin property by setting all margin properties using,

blockquote{
margin: 1em 0em 1em 0em;
}

The first part 1em is for margin-top and then it goes clockwise, second part is margin-right, then margin-bottom and then margin-left.

Let's assign some background colour all around blockquote. We can do this simply by background. Like,

blockquote{
margin: 1em 0em 1em 0em;
background: #AAA;
}

We will see that the background color barely covers the quoted text. But the margin area is not affected. However if we want that background color will be there will some amount of space around quote text(element) then we have to use another property of CSS called padding.

With usage of padding css code will look like,

blockquote{
margin: 1em 0em 1em 0em;
background: #AAA;
padding:.5em .5em .5em .5em;
}

Similar to margin padding can be padding-top, padding-right, padding-bottom, padding-left.

So, our final code will look like,

<html>
<style type="text/css">
blockquote{
margin: 1em 0em 1em 0em;
background: #AAA;
padding:.5em .5em .5em .5em;
}
</style>
<body>
In this blog http://arjudba.blogspot.com you will
see there is some space (though a very little amount)
all around. But there is no space whenever you
will disply this html code inside your browser.
<blockquote>
But there will be some spaces all around this
blockquote. Both left, right, top, bottom side.
</blockquote>
You are recommended to join http://arju-on-it.com/forum
and discuss your problems there
</body>
</html>

Final output is in,




No comments:

Post a Comment