Margin
Exercise
- In the "index.html" file, replace the code with the following:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS</title> <link rel="stylesheet" href="./css/styles.css"> </head> <body> <h1>Margin</h1> <p>This paragraph has no margin</p> <p id="margin-top">This paragraph has 50px of margin at the top.</p> <p id="margin-right">This paragraph has text aligned to the right and 30px of margin on the right.</p> <p id="margin-bottom">This paragraph has 20px of margin on the bottom.</p> <p id="margin-left">This paragraph has 60px of margin on the left.</p> <p id="margin-all">This paragraph has margin all around.</p> <p id="margin-1-value">This paragraph has 50px margin all around.</p> <p id="margin-2-values">This paragraph has 50px margin on top and bottom and 30px margin on left and right.</p> </body> </html>
- Save.
- If "Live Server" is not already running, right-click anywhere in the editor and select "Open with Live Server" from the context menu.
- In the "styles.css" file, replace the code with the following:
* { /* This removes the default margin of the browser */ margin: 0; } p { color: yellow; background-color: green; } #margin-top { margin-top: 50px; } #margin-right { text-align: right; margin-right: 30px; } #margin-bottom { margin-bottom: 20px; } #margin-left { margin-left: 60px; } #margin-all { margin: 50px 30px 20px 60px; } #margin-1-value { margin: 50px; } #margin-2-values { margin: 50px 30px; }
- Save.
- In the browser, you should see the following:
Code Walkthrough and Explanation
margin
In CSS, the margin
property is used to specify the space around an HTML element. It controls the
space
between the element's border and adjacent elements. The margin
property can be set with
different
values for each side of the element, allowing you to create different spacing around each side. You can specify
any
combination of values, depending on your requirements. For example, if you only specify one value, it will apply
to
all four sides. If you specify two values, the first value will apply to the top and bottom margins, and the
second
value will apply to the left and right margins. If you specify three values, the first value will apply to the
top
margin, the second value will apply to the left and right margins, and the third value will apply to the bottom
margin. If you specify four values, each value will apply to a specific side of the element (top, right, bottom,
left)
in that order. Margin can also be set for each side of an element (top, right, bottom, and left) using the
margin-top
, margin-right
, margin-bottom
, and margin-left
properties, respectively.
Experiment with the Code
- Try experimenting with different values of the
margin
properties.
Video and Code References
Questions? Subscribe and ask in the video comments: