margin-top
Definition
The margin-top property sets the top margin of an element. It specifies the space between the element's top edge and the adjacent elements in the document flow. A positive value moves the element down, while a negative value moves the element up.
Examples
Set the top margin of a paragraph to 20 pixels:
p {
margin-top: 20px;
}
Set the top margin of a header to 5% of the viewport height:
header {
margin-top: 5vh;
}
Set different top margins for different sections of a page:
#section1 {
margin-top: 50px;
}
#section2 {
margin-top: 100px;
}
#section3 {
margin-top: 150px;
}
Values
Value | Description |
---|---|
<length> | Specifies a fixed length for the margin in pixels, ems, rems, etc. |
<percentage> | Specifies a percentage of the height of the containing element. |
Best Practices
- Avoid using negative margin values whenever possible, as they can cause elements to overlap and make the layout difficult to read.
- Use the margin shorthand property instead of setting margin-top separately, especially if you need to set multiple margin values.
- Don't use margin-top to create rows in a layout. Instead, use CSS grid or flexbox for this purpose.
- Use relative units (ems, rems, etc.) instead of pixels for more flexible layouts that adapt to different screen sizes and devices.
- Consider using a CSS preprocessor like Sass or Less to simplify the process of setting margin values and avoid repetitive code.
Browser Compatibility
Chrome | Firefox | Safari | Internet Explorer | Microsoft Edge | Opera |
---|---|---|---|---|---|
Yes | Yes | Yes | Yes | Yes | Yes |