margin-top: 100px;
margin-bottom: 100px;
margin-right: 150px;
margin-left: 80px;
}
Shortened feature of margin in CSS
To shorten the code, it is possible to include all properties in a single margin property, with its own properties:
If margin has 4 values
margin: 25px 50px 75px 100px;
p {
margin: 25px 50px 75px 100px;
}
If the margin feature has 3 values
margin: 25px 50px 75px;
p {
margin: 25px 50px 75px;
}
If margin has 2 values
margin: 25px 50px;
p {
margin: 25px 50px;
}
If the margin property has 1 value
margin: 25px;
p {
margin: 25px;
}
Default value
When setting the margin
property to auto,
value auto,
it will automatically center the element horizontally. The element occupies the predetermined width, the rest will be divided equally for the left and right margins.
div {
width: 300px;
margin: auto;
border: 1px solid red;
}
Value inherit (inherited)
This example sets the left margin of the word section
class = 'ex1'> inherits from the parent element
div {
border: 1px solid red;
margin-left: 100px;
}
p.ex1 {
margin-left: inherit;
}
Collapse Margin
Sometimes the upper and lower margins of the elements overlap into a single margin equal to the size of the larger margin. This only happens with the top and bottom margins, not with the left and right margins.
h1 {
margin: 0 0 50px 0;
}
h2 {
margin: 20px 0 0 0;
}
In the above example, the lower margin of
is 50px and the upper margin of
is 20px. Usually the middle margin
and
will be the sum of both (i.e. 70px = 50px + 20px) but due to the alignment, this margin is only 50px.
Last lesson: Contour in CSS
The following article: Padding in CSS