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:
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:
<!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>