EN
JavaScript - element padding size in Vanilla JS
11 points
In this short article, we would like to show how to get the current padding of an element using JavaScript.
Presented below examples return padding in pixels - even different unit was used in styles.
Quick solution:
xxxxxxxxxx
1
var element = document.querySelector('#my-element');
2
var style = element.currentStyle || window.getComputedStyle(element);
3
4
console.log(parseInt(style.paddingLeft));
5
console.log(parseInt(style.paddingTop));
6
console.log(parseInt(style.paddingRight));
7
console.log(parseInt(style.paddingBottom));
This approach allows to get current style value (even was assigned with selector).
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
body {
7
margin: 0;
8
height: 140px;
9
}
10
11
div {
12
/* 2em=32px */
13
padding: 2em 30px 40px 10px; /* [top] [right] [bottom] [left] */
14
background: gray;
15
width: 100px; height: 100px;
16
}
17
18
</style>
19
</head>
20
<body>
21
<div id="my-element">Text...</div>
22
<script>
23
24
var element = document.querySelector('#my-element');
25
var style = element.currentStyle || window.getComputedStyle(element);
26
27
console.log('padding-left:' + parseInt(style.paddingLeft));
28
console.log('padding-top:' + parseInt(style.paddingTop));
29
console.log('padding-right:' + parseInt(style.paddingRight));
30
console.log('padding-bottom:' + parseInt(style.paddingBottom));
31
32
</script>
33
</body>
34
</html>
This approach organized the above code in a reusable function.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
body {
7
margin: 0;
8
height: 140px;
9
}
10
11
div {
12
padding: 20px 30px 40px 10px; /* [top] [right] [bottom] [left] */
13
background: gray;
14
width: 100px; height: 100px;
15
}
16
17
</style>
18
<script type="text/javascript">
19
20
function getPadding(element) {
21
var style = element.currentStyle || window.getComputedStyle(element);
22
23
var result = {
24
getLeft: function() {
25
return parseInt(style.paddingLeft);
26
},
27
getTop: function() {
28
return parseInt(style.paddingTop);
29
},
30
getRight: function() {
31
return parseInt(style.paddingRight);
32
},
33
getBottom: function() {
34
return parseInt(style.paddingBottom);
35
}
36
};
37
38
return result;
39
}
40
41
</script>
42
</head>
43
<body>
44
<div id="my-element">Text...</div>
45
<script>
46
47
var element = document.querySelector('#my-element');
48
var padding = getPadding(element);
49
50
console.log('padding-left:' + padding.getLeft());
51
console.log('padding-top:' + padding.getTop());
52
console.log('padding-right:' + padding.getRight());
53
console.log('padding-bottom:' + padding.getBottom());
54
55
</script>
56
</body>
57
</html>