The CSS margin defines the space around an HTML element (like <body>, <div>, <img> etc). We used to mark margins while writing with pen and paper to enhance readability and presentation. Likewise the webpage contents do need margins. The CSS margin property let you take control of the entire webpage elements and set margins entirely or to an individual element in a webpage. You have already got a glimpse of using css margins in the post Different ways to add CSS styles to an HTML Page. Here let us see in detail.
As you can see from the above image, there are four margin properties to be set for an html element. They are,
Note: The value can be of units (like pixel, point etc), percentage or auto.
All the four css margin properties can be defined in a single line. It has the syntax,
margin: margin-top margin-right margin-bottom margin-left;
The css margin property takes up 4, 3, 2 or a single parameter.
CSS Margin with Four Parameters:
If you want to set margin of 10 pixels to the top, 15 pixels to the bottom and left and right to spare 5 pixels of margin space, then you can use,
margin: 10px 5px 15px 5px;
CSS Margin with Three Parameters:
In the above example the left and right margins are both 5px, so we can rewrite it with three parameters.
margin: 10px 5px 15px;
The margins will be set as top => 10px, left/right => 5px and bottom => 15px.
If we don’t provide the fourth value, the browser assigns the value of its opposite side margin. So the right margin value will be taken up for the left margin.
CSS Margin with Two Parameters:
If top-bottom margins and left-right margins are of the same value then it can be written with two parameters like below
margin: 10% 0;
- First parameter refers to top, bottom margin values
- Second parameter refers to left, right margin values
Note: If there is no margin for a side then it should be given as 0. No need for adding px to 0.
CSS Margin with Single Parameter:
If all the four margins are of same value then it can written with a single parameter like below,
Here all the four margins will be set to 10 pixels.
If you want to position a block-level container (like <body>, <div>) in the center of its parent container, then set its left and right margins to auto value. You must set the width of the container in order to avoid the container’s width stretched to match its parent container.
To place a block at the center with its top and bottom margins of 10px, you could use,
margin: 10px auto;
margin: 10px auto;
Note: Center aligning has no effect if the width is set to the same value as of parent container or 100%