CHAPTER 9

CSS Margins

CSS margin properties control the outside spacing around an element.

01. What is CSS Margins?

Margin creates space outside an element.
margin-top controls top spacing.
margin-right controls right spacing.
margin-bottom controls bottom spacing.
margin-left controls left spacing.
margin: auto can be used to center a fixed-width block horizontally.

02. Syntax

.box { margin: 20px; } .card { margin: 20px auto; }

03. Example

CSS / HTML Example AIFA Coding Lab
<!DOCTYPE html>
<html>

<head>

    <style>

        .card {

            width: 300px;

            padding: 25px;

            background: #eef6ff;

            margin:
                40px auto;

            border-radius:
                15px;

        }

    </style>

</head>

<body>

    <div class="card">

        <h2>
            CSS Margin
        </h2>

        <p>
            This card is centered
            using margin auto.
        </p>

    </div>

</body>

</html>

04. Important Points

✓ Margin creates outside space.
✓ Margin is different from padding.
✓ margin: auto is commonly used to center fixed-width block elements.

05. Common Mistakes

⚠ Confusing margin with padding.
⚠ Expecting margin auto to vertically center every element.
⚠ Forgetting that margin behavior can vary depending on layout context.

06. Real World Use

Margins are used to create spacing between cards, sections, headings, buttons and other page elements.

Ready to Practice? 🚀

Open the AIFA CSS Editor and practice this chapter live.

Try It Yourself →
Practice Exercise

Practice Margins

Create three cards and use different margins to control the spacing between them.