Margins
Part of the Styling with CSS section of Coddy's HTML journey — lesson 35 of 76.
In CSS, margin is the space around an element, outside of any defined borders. It is another essential part of the box model. Margins are used to create space between elements, separating them from each other.
You can control the margin on all four sides of an element (top, right, bottom, and left) independently or using shorthand notation.
Here's the basic syntax for using the margin property:
selector {
margin-top: value;
margin-right: value;
margin-bottom: value;
margin-left: value;
}margin-top: The margin on the top side of the element.margin-right: The margin on the right side of the element.margin-bottom: The margin on the bottom side of the element.
margin-left: The margin on the left side of the element.value: The desired margin value, which can be specified in pixels (px), ems (em), percentages (%), or other valid CSS units.
You can also use shorthand notation to set the margin for all four sides at once, for example:
p {
margin: 20px; /* Applies the same margin to all four sides */
}
div {
margin: 10px 25px; /* Sets top and bottom margin to 10px, and left and right margin to 25px */
}
.button {
margin: 15px 30px 10px 5px;/* Sets margin for each side individually */
}In this example, all <p> elements have a margin of 20px on all sides, all <div> elements have a top and bottom margin of 10px and a left and right margin of 25px, and all elements with the class button have a top margin of 15px, a right margin of 30px, a bottom margin of 10px, and a left margin of 5px.
Challenge
EasyYou are given an HTML document with a heading (<h1>) and a division (<div>). Your task is to use the margin property to add space around these elements. Follow the steps below:
- Write a CSS rule that targets the
<h1>element. Set themarginto20pxon all sides. - Write a CSS rule that targets the
<div>element. Set the top and bottommarginto10pxand the left and rightmarginto30px.
Cheat sheet
The margin property creates space around an element, outside of any borders. You can control margin on all four sides independently or use shorthand notation.
Individual margin properties:
selector {
margin-top: value;
margin-right: value;
margin-bottom: value;
margin-left: value;
}Shorthand notation:
/* Same margin on all sides */
margin: 20px;
/* Top/bottom: 10px, Left/right: 25px */
margin: 10px 25px;
/* Top: 15px, Right: 30px, Bottom: 10px, Left: 5px */
margin: 15px 30px 10px 5px;Try it yourself
<html>
<head>
<title>Margins</title>
<style>
/* Write CSS rules here */
</style>
</head>
<body>
<h1 style="border:2px solid black;">Mastering CSS Margins</h1>
<div style="border:2px solid black;">Margins create space around elements.</div>
</body>
</html>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Styling with CSS
5 Colors and Backgrounds
Background ColorHEX ColorsRGB ColorsTransparency with RGBARecap Challenge #1