About Lesson
Definition:
In CSS, the margin
property is used to control the space outside an element’s border. It defines the amount of space between an element’s border and surrounding elements.
Syntax:
HTML
selector {
margin: value;
}
The value
can be set using various units, such as pixels (px
), em, rem, percentages (%), etc. You can also specify values for individual sides (top, right, bottom, left) using the margin-top
, margin-right
, margin-bottom
, and margin-left
properties.
Example:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
/* Apply margin to a div with the class 'box' using shorthand property */
.box {
margin: 20px; /* Applies 20px margin to all sides */
background-color: lightblue;
padding: 10px;
border: 2px solid navy;
}
/* Apply margin to a paragraph with the class 'paragraph' using individual properties */
.paragraph {
margin-top: 10px;
margin-right: 30px;
margin-bottom: 10px;
margin-left: 30px;
background-color: lightgreen;
padding: 10px;
border: 2px solid darkgreen;
}
</style>
<title>Margin Example</title>
</head>
<body>
<div class="box">
This is a box with margin applied using the shorthand property.
</div>
<p class="paragraph">
This is a paragraph with margin applied individually for each side.
</p>
</body>
</html>
In this example:
- The first CSS rule applies a
margin
of20px
to all sides of adiv
element with the classbox
. It also sets a light blue background, padding, and a navy border. - The second CSS rule applies different margins to each side of a
p
element with the classparagraph
. It sets a light green background, padding, and a dark green border.
You can customize the margin
values to create the desired spacing around your elements. Using the shorthand property is common for applying equal margins to all sides, while individual properties offer more control over each side’s margin.