CSS Padding
- Purpose: Creates space inside the element’s border. It controls the distance between the content of the element and its border.
- Syntax: element {padding: top right bottom left; }
- Shorthand: You can use shorthand values:
- padding: 10px; (sets the same padding for all sides)
- padding: 10px 20px; (sets top/bottom padding to 10px and left/right padding to 20px)
- padding: 10px 20px 30px; (sets top padding to 10px, left/right padding to 20px, and bottom padding to 30px)
- Example:
div {
padding: 10px;
}
This will add 10 pixels of space between the content of the <div> element and its border on all sides.
CSS Margin
- Purpose: Creates space outside the element’s border. It controls the distance between the element and its neighboring elements.
- Syntax: element { margin: top right bottom left;}
- element: The HTML element you want to style (e.g., p, h1, span).
- Shorthand: You can use shorthand values:
- padding: 10px; (sets the same padding for all sides)
- padding: 10px 20px; (sets top/bottom padding to 10px and left/right padding to 20px)
- padding: 10px 20px 30px; (sets top padding to 10px, left/right padding to 20px, and bottom padding to 30px)
- Example:
p {
margin: 20px 0;
}
This will add a 20-pixel margin above and below each <p> element, but no margin to the left or right.
Key Difference between Padding and Margin
- Location: padding affects the space inside the element’s border, while margin affects the space outside the border.
- Impact on Layout: margin directly affects the layout and positioning of elements on the page.