CSS Margin Property – Adding space outside an element

CSS

0 Comments

The margin property adds some space around the outside of an element.

Example

<style>
	.btn {
		margin-right: 10px;
	}
</style>

<input type="button" class="btn" value="Button 1">
<input type="button" class="btn" value="Button 2">

Result

.btn selector (Line 2)
Says we want to style all elements that were given the btn class.
The period before btn means btn is a class.
margin-right property (Line 3)
Add 10 pixels of space (margin) to the right of each button.
If you don't know what pixels are, they are the tiny dots on your monitor that create the picture you see.
Each line of CSS should end with a semi-colon (;).

The many ways to specify a margin

margin-top
Add space above the element.
margin-bottom
Add space below.
margin-right
Add space on the right.
margin-left
Add space on the left

Shortcuts (to specify all of these at once):

/* This is a comment in CSS */

.btn {
    /* Give 10px of space on every side */
    margin: 10px;

    /* top, right, bottom, left */
    margin: 10px 20px 30px 40px;

    /* 10px for top/bottom and 20px for left/right */
    margin: 10px 20px;

    /* 10px for top, 20px for left/right, 30px for bottom */
    margin: 10px 20px 30px;
}
/* CSS comments */ (Line 1)
This is a comment in CSS. Comments are basically notes for the programmer and are ignored by the browser. They start with /* and end with */ (and can span 1 or more lines).

Practice in Editor

Leave a Comment