CSS Padding vs Margin Explained
Q: Can you explain the difference between padding and margin in CSS and how they are used to create spacing between elements?
- CSS
- Junior level question
Explore all the latest CSS interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create CSS interview for FREE!
In CSS, padding and margin are two types of spacing
properties that are used to create space between elements.
- Padding:
Padding is the space between an element's content and its border. It is
used to add space within an element. Padding is set using the 'padding'
property and can be specified in pixels, ems, or percentages. For example,
to add 10 pixels of padding to an element, you would use the following CSS
code:
.my-element { padding: 10px; }
- Margin:
Margin is the space between an element's border and the adjacent elements.
It is used to add space between elements. Margin is set using the 'margin'
property and can be specified in pixels, ems, or percentages. For example,
to add 10 pixels of margin to an element, you would use the following CSS
code:
.my-element { margin: 10px; }
The main difference between padding and margin is that
padding adds space within an element, while margin adds space between elements.
Padding affects the size of an element's content box, while margin affects the
spacing between adjacent elements.
To create spacing between elements, you can use margin to
add space between elements, or you can use padding to add space within an
element. For example, to add space between two paragraphs, you can use margin:
p { margin-bottom: 10px; }
Or to add space within a paragraph, you can use padding:
p { padding: 10px; }
Overall, padding and margin are both important spacing
properties in CSS that are used to create visually appealing layouts and
improve the readability of web content.


