The padding
property sets or gets the padding of an element.
padding can have one to four values.
padding:10px 5px 15px 20px;
padding:10px 5px 15px;
padding:10px 5px;
padding:10px;
padding |
Yes | Yes | Yes | Yes | Yes |
Return the padding property:
var v = object.style.padding;
Set the padding property:
object.style.padding='%|length|initial|inherit'
Value | Description |
---|---|
auto | Default value. The browser does the calculation. |
length | Set width in px, cm, etc. |
% | Set width in percent of the containing element |
inherit | Inherit the width property from the parent element |
Default Value: | 0 |
---|---|
Return Value: | A string representing the padding |
CSS Version | CSS1 |
The following code shows how to Set the padding of a <div> element:
<!DOCTYPE html>
<html>
<head>
<style>
#myDiv {<!--from w ww .j a va2s . c om-->
border: 1px solid #FF0000;
}
</style>
</head>
<body>
<div id="myDiv">This is a div.</div>
<button type="button" onclick="myFunction()">test</button>
<script>
function myFunction() {
document.getElementById("myDiv").style.padding = "50px 10px 20px 30px";
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to change the padding of all four sides of a <div> element to "25px".
<!DOCTYPE html>
<html>
<head>
<style>
#myDiv {<!--from w ww .j av a 2 s .c o m-->
border: 1px solid #FF0000;
padding: 2cm 4cm 3cm 2cm;
}
</style>
</head>
<body>
<div id="myDiv">This is a div.</div>
<button type="button" onclick="myFunction()">test</button>
<script>
function myFunction() {
document.getElementById("myDiv").style.padding = "25px";
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to return the padding of a <div> element.
<!DOCTYPE html>
<html>
<head>
<style>
#myDiv {<!-- w w w .j ava 2s . c o m-->
border: 1px solid #FF0000;
}
</style>
</head>
<body>
<div id="myDiv" style="padding:2cm 4cm 3cm 5cm;">This is a div.</div>
<button type="button" onclick="myFunction()">test</button>
<script>
function myFunction() {
console.log(document.getElementById("myDiv").style.padding);
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to set the margin property and the padding property.
<!DOCTYPE html>
<html>
<head>
<style>
div {<!-- w w w.j ava 2 s.c o m-->
border: 1px solid red;
}
</style>
</head>
<body>
<div id="myDiv">This is some text.</div>
<button type="button" onclick="changeMargin()">Change margin</button>
<div id="myDiv2">This is some text.</div>
<button type="button" onclick="changePadding()">Change padding</button>
<script>
function changeMargin() {
document.getElementById("myDiv").style.margin = "100px";
}
function changePadding() {
document.getElementById("myDiv2").style.padding = "100px";
}
</script>
</body>
</html>
The code above is rendered as follows: