9️⃣

4.9 Box Model Margin

The CSS margin properties are used to create space around elements, outside of any defined borders.
With CSS, you have full control over the margins. There are properties for setting the margin for each side of an element (top, right, bottom, and left).

Margin - Individual Sides

CSS has properties for specifying the margin for each side of an element:
  • margin-top
  • margin-right
  • margin-bottom
  • margin-left
All the margin properties can have the following values:
  • auto - the browser calculates the margin
  • length - specifies a margin in px, pt, cm, etc.
  • % - specifies a margin in % of the width of the containing element

Margin - Shorthand Property

To shorten the code, it is possible to specify all the margin properties in one property.
The margin property is a shorthand property for the individual margin properties.
If the margin property has four values:
  • margin: 25px 50px 75px 100px;
    • top margin is 25px
    • right margin is 50px
    • bottom margin is 75px
    • left margin is 100px
If the margin property has three values:
  • margin: 25px 50px 75px;
    • top margin is 25px
    • right and left margins are 50px
    • bottom margin is 75px
If the margin property has two values:
  • margin: 25px 50px;
    • top and bottom margins are 25px
    • right and left margins are 50px
If the margin property has one value:
  • margin: 25px;
    • all four margins are 25px

The auto Value

You can set the margin property to auto to horizontally center the element within its container.
The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.
notion image

Previous Section

8️⃣
4.8 CSS Outline
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.