Which property specifies the top margin of an element in CSS ?
In this article, we are going to discuss the margin-top property that specifies the top margin of an element.
In order to specify the top margin of an element, CSS provides a styling element called margin-top which sets the top margin of an element. This property accepts an integer value. The default value is 0 and negative values are also allowed. The syntax of the margin-top property is given below.
Syntax:
margin-top: length | auto | initial | inherit;
Property Values:
- length: The length parameter specifies the length of the top margin in px, cm, %.
- auto: The browser itself auto-sets the top margin.
- initial: Sets the property to the default value.
- inherit: It inherits the property value from the parent components.
Let’s look into a few examples of specifying the top margin of an element.
Example 1: In this example let’s see the difference between an element having a top margin and an element without top-margin property.
HTML
<!DOCTYPE html>
< html >
< head >
< style >
p#p1 {
margin-top: 50px;
}
</ style >
</ head >
< body >
< h2 >Welcome To GFG</ h2 >
< p id = "p1" >Top Margin set to 50px</ p >
< p >No top margin</ p >
</ body >
</ html >
|
Output:
Example 2: Here in the below code Let’s try to apply each property value of top-margin to the <h4> elements.
HTML
<!DOCTYPE html>
< html >
< head >
< style >
.parent {
margin-top: 1.5cm;
}
h4.p1 {
margin-top: 20px;
}
h4.p2 {
margin-top: 8%;
}
h4.p3 {
margin-top: auto;
}
h4.p4 {
margin-top: initial;
}
h4.p5 {
margin-top: inherit;
}
</ style >
</ head >
< body >
< h4 class = "p1" >Top-margin:20px</ h4 >
< h4 class = "p2" >Top-margin:8%</ h4 >
< h4 class = "p3" >Top-margin:auto</ h4 >
< h4 class = "p4" >Top-margin:initial</ h4 >
< div class = "parent" >
< h4 class = "p5" >Top-margin:inherit</ h4 >
</ div >
</ body >
</ html >
|
Output:
Last Updated :
30 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...