Propriedade de estilo margem

Definição e uso

margem A propriedade define ou retorna a margem do elemento.

Este atributo pode usar de um a quatro valores:

  • Um valor, por exemplo: div {margin: 50px} - Todas as quatro margens externas são de 50px
  • Dois valores, por exemplo: div {margin: 50px 10px} - A margem superior e inferior externa é de 50px, e a margem lateral externa é de 10px
  • Três valores, por exemplo: div {margin: 50px 10px 20px} - A margem superior externa é de 50px, a margem lateral externa é de 10px, e a margem inferior externa é de 20px
  • Four values, for example: div {margin: 50px 10px 20px 30px} - the top margin is 50px, the right margin is 10px, the bottom margin is 20px, and the left margin is 30px

Both margin property and padding property insert space around the element. However, the difference is that margin inserts space around the border, while padding inserts space inside the element's border.

See also:

CSS tutorial:Margem externa do CSS

CSS reference manual:Margin property

Instance

Example 1

Set all four margins of the <div> element:

document.getElementById("myDiv").style.margin = "50px 10px 20px 30px";

Try it yourself

Example 2

Change all four margins of the <div> element to "25px":

document.getElementById("myDiv").style.margin = "25px";

Try it yourself

Example 3

Return the margin of the <div> element:

alert(document.getElementById("myDiv").style.margin);

Try it yourself

Example 4

Difference between margin property and padding property:

function changeMargin() {
  document.getElementById("myDiv").style.margin = "100px";
}
function changePadding() {
  document.getElementById("myDiv2").style.padding = "100px";
}

Try it yourself

Syntax

Return margin property:

object.style.margin

Set margin property:

object.style.margin = "%|length|auto|initial|inherit"

Property value

Value Description
% Define margin using the percentage of the parent element's width.
length Define margin using length units.
auto Browser sets margin (all four margins will be equal).
initial Sets this property to its default value. See initial.
inherit Inherits this property from its parent element. See inherit.

Technical details

Default value: 0
Return value: String, representing the element's margin.
Versão do CSS: CSS1

Suporte ao navegador

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
Suporte Suporte Suporte Suporte Suporte