totn CSS

CSS: margin-top property

This CSS tutorial explains how to use the CSS property called margin-top with syntax and examples.

Description

The CSS margin-top property defines the margin on the top of an element.

Syntax

The syntax for the margin-top CSS property is:

margin-top: value;

Parameters or Arguments

value

The margin to apply to the top of the element. It can be one of the following:

Value Description
fixed Fixed value expressed in px, em, ...
div { margin-top: 8px; }
div { margin-top: 3em; }
percentage Percentage value
div { margin-top: 5%; }
auto Used for centering blocks
div { margin-top: auto; }
inherit Element will inherit the margin-top from its parent element
div { margin-top: inherit; }

Note

  • The value in the CSS margin-top property can be expressed as either a fixed value or as a percentage.
  • Negative values are allowed in the CSS margin-top property.
  • When the value is provided as a percentage, it is relative to the width of the containing block.
  • See also margin, margin-bottom, margin-left, and margin-right.

Browser Compatibility

The CSS margin-top property has basic support with the following browsers:

  • Chrome
  • Android
  • Firefox (Gecko)
  • Firefox Mobile (Gecko)
  • Internet Explorer (IE)
  • IE Phone
  • Opera
  • Opera Mobile
  • Safari (WebKit)
  • Safari Mobile

Example

We will discuss the margin-top property below, exploring examples of how to use this property in CSS with a fixed value as well as a percentage value.

Using Fixed Value

Let's look at a CSS margin-top example where we have provided the value as a fixed value.

div { margin-top: 5px; }

In this CSS margin-top example, we have provided a value of 5px which would apply to the top of the element.

Let's look at another CSS margin-top example with a fixed value.

div { margin-top: 10em; }

In this CSS margin-top example, we have provided a value of 10em which would apply to the top of the element.

Using Percentage

Let's look at a CSS margin-top example where we have provided the value as a percentage.

div { margin-top: 10%; }

In this CSS margin-top example, we have provided a value of 10% which would apply to the top of the element.

Using Auto

Let's look at an example where we have provided the value as auto.

div { margin-top: auto; }

In this example, we have set the top margin to auto for the <div> tag. The auto value is generally used to center blocks.