CSS Margin and Padding Properties
Box model
CSS Margins
Margins are used to create space around elements, outside of any defined borders.
<!DOCTYPE html>
<html>
<head>
<style>
div {
margin: 70px;
border: 1px solid #4CAF50;
}
</style>
</head>
<body>
<h2>CSS Margins</h2>
<div>This element has a margin of 70px.</div>
</body>
</html>
The CSS margin properties are used to create space
around elements, outside of any defined borders.
With CSS, you have full control over the margins.
There are properties for setting the margin for each
side of an element (top, right, bottom, and left).
Margin - Individual Sides
CSS has properties for specifying the margin for each
side of an element:
margin-top
margin-right
margin-bottom
margin-left
All the margin properties can have the following
values:
auto - the browser calculates the margin
length - specifies a margin in px, pt, cm, etc.
% - specifies a margin in % of the width of the
containing element
inherit - specifies that the margin should be inherited
from the parent element
p {
margin-top: 100px;
margin-bottom: 100px;
margin-right: 150px;
margin-left: 80px;
}
Margin - Shorthand Property
If the margin property has four values:
margin: 25px 50px 75px 100px;
top margin is 25px
right margin is 50px
bottom margin is 75px
left margin is 100px
If the margin property has three values:
margin: 25px 50px 75px;
top margin is 25px
right and left margins are 50px
bottom margin is 75px
CSS Padding
Padding is used to create space around an element's
content, inside of any defined borders.
The CSS padding properties are used to generate space
around an element's content, inside of any defined
borders.
With CSS, you have full control over the padding.
There are properties for setting the padding for each
side of an element (top, right, bottom, and left).
Padding - Individual Sides
CSS has properties for specifying the padding for each
side of an element:
padding-top
padding-right
padding-bottom
padding-left
All the padding properties can have the following
values:
length - specifies a padding in px, pt, cm, etc.
% - specifies a padding in % of the width of the
containing element
inherit - specifies that the padding should be inherited
from the parent element
CSS Box Model
All HTML elements can be considered as boxes.
In CSS, the term "box model" is used when talking
about design and layout.
The CSS box model is essentially a box that wraps
around every HTML element. It consists of: margins,
borders, padding, and the actual content. The image
below illustrates the box model:
Explanation of the different parts:
Content - The content of the box, where text and
images appear
Padding - Clears an area around the content. The
padding is transparent
Border - A border that goes around the padding and
content
Margin - Clears an area outside the border. The margin
is transparent
The box model allows us to add a border around
elements, and to define space between elements.