How to Make Margins in CSS
Margins in Web pages refer to the spacing between HTML elements. You can think of each HTML element -- paragraphs, headings, images and other parts of Web pages -- as boxes, and margins represent the spacing between each box. The margins between two boxes lined up next to each other on a page will overlap. Margins are set using Cascading Style Sheet code using the "margin" properties. Set margins to specific parts of your page or every element of a type, such as all paragraphs.
Instructions
-
-
1
Open the Web page in Notepad or a code editor and look for "<style>" tags between the "<head>" tags at the top of your code. Add this code if you see no "<style>" tags:
<style type="text/css">
</style>
-
2
Find the content where you want to apply margin settings. Look at the tags that surround the content and get an ID name from them:
<div id="box">
<h2>Heading</h2>
<p>Content text here...</p>
</div>
In the example, you need the ID "box" from the "<div>" tag to add margins to the entire div. Add an ID to the "<h2>" heading tag to set margins for the heading in the example.
-
-
3
Go back to your "<style>" tags and write your CSS code between them. Add a style rule that selects content from the page by its ID name:
#box {
}
The hash symbol prefixes an ID name in CSS.
-
4
Add margin settings between the curly braces of the style rule:
#box {
margin-top: 10px;
margin-left: 20px;
margin-right: 30px;
margin-bottom: 40px;
}
You can set each margin separately using one of the properties from the above sample, such as "margin-top". The equivalent short-hand form of this code is "margin: 10px 20px 30px 40px". This code goes clockwise around the content, starting from the top. To set all margins to the same value, use "margin: 10px" instead.
-
5
Set margins for all tags of one type using this style rule:
p {
margin: 10px;
}
The "p" stands for the "<p>" tag in HTML. Use "h2" for the "<h2>" tag and so on.
-
1
Tips & Warnings
Set your right and left margins to "auto" to center an HTML element on the page.