WEEK: 9
Active: Not Currently Active
Work Due:

Margin

Look back to our box model, we can see that the margin, is the space between the box/element and other elements or the edge of the parent element.

The Box Model
Margin
Border
Padding
The Content!

As with padding, margin accepts both absolute and relative size units.

Example 1

In the following example, look at the two containers, and how the are positioned, based on the margin settings.

CSS
.parent-container-01 {
    background-color: #83e672;
    width: 400px;
    height: 400px;
}
.child-container-01 {
    background-color: #ed60ff;
    width: 50%;
    height: 50%;
}
.parent-container-02 {
    background-color: #83e672;
    width: 400px;
    height: 400px;
    margin: 2%;
}
.child-container-02 {
    margin: 10%;
    background-color: #ed60ff;
    width: 50%;
    height: 50%;
}
HTML
<div class="parent-container-01">
    <div class="child-container-01"></div>
</div>
<div class="parent-container-02">
    <div class="child-container-02"></div>
</div>
[View on GitHub] [Live Example]

Example 2

In the next example, notice how the ‘.child-container-03’, has both margin and padding properties set. Also notice, that the parent-container has neither. Note that the browser does not allow the child container’s margin to push the height of the parent container. However, it does still create space between the top of the containing window and both the parent and child elements.

CSS
body {
    font-size: 18pt;
}
.parent-container-03 {
    background-color: #83e672;
}
.child-container-03 {
    margin: 6em;
    padding: 3em;
    background-color: #ed60ff;
}
HTML
<body>
    <div class="parent-container-03">
        <div class="child-container-03"></div>
    </div>
</body>
[View on GitHub] [Live Example]

Using Margin to Set Center Alignment

The margin property is also used to center align element, horizontally, in there parent elements. This can be accomplished by setting the properties value to auto, or by setting both margin-left: auto; & margin-right: auto;.

CSS
.parent-container-04 {
    background-color: #83e672;
    padding: 1em;
}
.child-container-04 {
    margin-left: auto;
    margin-right: auto;
    margin-top: 1em;
    margin-bottom: 2em;
    max-width: 14em;
    text-align: center;
    padding: 2em;
    color: #fff;
    background-color: #ed60ff;
}
HTML
<div class="parent-container-04">
    <div class="child-container-04">
        <em>I'm in the middle!</em>
    </div>
</div>
I'm in the middle!
[View on GitHub] [Live Example]

Previous section:
Next section: