what is the difference between margin & padding ?
wy we use them ?

Recommended Answers

All 5 Replies

-------------------
|     padding     |
|                 |
|                 |
|                 |
-------------------
margin

Padding moves items inside the element away from the border of the element.
Margin moves items away from other items.

margin affects the height and width of an element. Whereas padding affects the space inside the element for the child elements to fill.
Say if you had a parent div with the class "parent" and some text inside it:

<html>
    <body>
        <div class="parent">
            <h1>A header which will be contained within the parent div</h1>
            <h2>a sub heading</h2>
        </div>
    </body>
</html>

with the styling as follows:

div.parent {
    height:180px;
    width:400px;
    padding:15px;
    margin:20px;
}

the padding will give the text inside the "parent" div less room to fill.
the margin will push the "parent" div away from other elements so if there was a specific space the div had to fill (400x180) it will actually fill (440x220) because of the margins all round.

I hope this helps.

In addition to the information that's already been presented in this thread, I think a visual aid would be helpful. To better understand padding and margin, you should understand the concept of the CSS Box Model. All of these attributes affect the overal size of the actual space taken up by the element.

0347008eca745add0a0862af7f97ec1b

Source: CSS Box Model

Find the attached image for more clearification regarding Margin & Padding - 3cf29905c4a515a24556c7d869a599a3

-Mike

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.