Style marginTopPropiedad
Objeto Style
Definición y uso
La propiedad marginTop establece o devuelve el margen superior exterior de un elemento.
Sintaxis
Establecer la propiedad marginTop:
Object.style.marginTop="%|length|auto|inherit"
Devolver la propiedad marginTop:
Object.style.marginTop
| Valor | Descripción |
|---|---|
| % | Define un margen superior como un porcentaje del ancho del elemento padre. |
| length | Define el ancho del margen superior en unidades como px, cm, etc. |
| auto | El margen superior establecido por el navegador. |
| inherit | El margen superior se hereda del elemento padre. |
Compatibilidad del navegador
![]()
![]()
![]()
![]()
![]()
Todos los navegadores principales admiten la propiedad marginTop.
Nota:IE7 y versiones anteriores no admiten el valor "inherit". IE8 solo admite "inherit" si se especifica !DOCTYPE. IE9 admite "inherit".
Sugerencias y notas
Las propiedades margin y padding insertan espacio alrededor de un elemento. Sin embargo, la diferencia es que margin inserta espacio fuera del borde, mientras que padding inserta espacio dentro del borde del elemento.
Ejemplo
Ejemplo
Cambiar el margen superior de un elemento div:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tutorial para novatos (example.com)</title>
<style type="text/css">
div{
border: 1px solid #FF0000;
}
</style>
<script>
function changeMargin(){
document.getElementById("ex1").style.marginTop="100px";
}
function changePadding(){
document.getElementById("ex2").style.paddingTop="100px";
}
</script>
</head>
<body>
<div id="ex1">Este es un texto.</div>
<br>
<button type="button" onclick="changeMargin()">Cambiar el margen superior del elemento div</button>
<br>
<br>
<div id="ex2">Este es un texto.</div>
<br>
<button type="button" onclick="changePadding()">Cambiar el padding superior del elemento div</button>
</body>
</html>
<html>
<head>
<meta charset="utf-8">
<title>Tutorial para novatos (example.com)</title>
<style type="text/css">
div{
border: 1px solid #FF0000;
}
</style>
<script>
function changeMargin(){
document.getElementById("ex1").style.marginTop="100px";
}
function changePadding(){
document.getElementById("ex2").style.paddingTop="100px";
}
</script>
</head>
<body>
<div id="ex1">Este es un texto.</div>
<br>
<button type="button" onclick="changeMargin()">Cambiar el margen superior del elemento div</button>
<br>
<br>
<div id="ex2">Este es un texto.</div>
<br>
<button type="button" onclick="changePadding()">Cambiar el padding superior del elemento div</button>
</body>
</html>
Pruébalo »
Objeto Style Otras extensiones